【问题标题】:Javascript - Vue js fetch from fileJavascript - Vue js 从文件中获取
【发布时间】:2018-03-05 17:34:00
【问题描述】:

我只是在学习 Vue js,并通过在 html 末尾包含源代码以最简单的方式使用它。现在我正在尝试像这样进行普通的 javscript 获取:

fetch('./json_docs/example.json')
   .then(function(response) {
      return response;
   })
   .then(function(res) {
      console.log(res);
  });

我得到的响应看起来像这样,但我没有得到实际数据。当我尝试使用浏览器响应中包含的文件的 url 时,数据显示。有谁知道我做错了什么?

Response { type: "basic", url: "file:///Users/danielamir/Documents/…", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, bodyUsed: false }

【问题讨论】:

  • response 上致电.json。见Making Fetch Requests
  • 似乎不起作用,当我记录 response.json @zero298 时它只是返回'function json()'
  • 调用它与 .json() 使用括号。看我的回答。
  • 另外,在响应的 URL 中看到 file:// 让我担心。您如何提供此内容?你地址栏的网址里有file://吗?
  • 我得到一个文件只是为了测试,所以这就是@zero298

标签: javascript api vue.js get fetch


【解决方案1】:

您需要在response 上实际调用.json

fetch('./json_docs/example.json')
   .then(function(response) {
      return response.json(); // As a function call
   })
   .then(function(data) {
      console.log(data);
  });

Making Fetch Requests

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-29
    • 2020-09-06
    • 1970-01-01
    • 2020-02-10
    • 2017-08-06
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    相关资源
    最近更新 更多