未捕获(承诺)TypeError:response.json 不是函数

新手上路,请多包涵

我正在尝试从我的 firebase 后端加载数据但收到此错误

Uncaught (in promise) TypeError: response.json is not a function

我的代码如下:

 import axios from 'axios';
export const loadData = ({ commit }) => {
  console.log('getting data from server...');

  axios
    .get('data.json')
    .then(response => response.json())
    .then(data => {
      if (data) {

        const stocks = data.stocks;
        const stockPortfolio = data.stockPortfolio;
        const funds = data.funds;

        const portfolio = {
          stockPortfolio,
          funds
        };
        commit('SET_STOCKS', stocks);
        commit('SET_PORTFOLIO', portfolio);
        console.log('Commit done ');
      }
    });
};

但是,如果我尝试 response.data 而不是 response.json 它可以工作并成功加载数据,所以我很好奇有什么区别以及为什么第一个不起作用。

原文由 skr 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 716
2 个回答

由于 axios 包,它有一个特定的响应模式 https://github.com/axios/axios#response-schema

 The response for a request contains the following information.

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}

原文由 Evgeny Skarlat 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 axios,您不需要额外的 .json() 。响应已经作为 javascript 对象提供,无需解析,只需获取响应和访问数据即可。你可以直接使用类似

axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

原文由 joy08 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题