我正在尝试从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,它可以工作并成功加载数据,所以我很好奇有什么区别以及为什么第一个不起作用。
答案 0 :(得分:1)
由于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: {}
}
答案 1 :(得分: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);
});
答案 2 :(得分:0)
如果您试图从Response
流中解析承诺,则只需要使用Body.json()方法。您可以在documentation上阅读有关它的更多信息。这样做的一种用例是使用fetch API发出HTTP请求时,您将必须调用Body.json()
返回响应正文。
let response = await fetch(url);
if (response.ok) { // if HTTP-status is 200-299
// get the response body (the method explained below)
let json = await response.json();
} else {
alert("HTTP-Error: " + response.status);
}
对于axios,您只需要在发出GET请求后解决该问题
axios.get(url[, config])
因此,下面的代码可以正常工作,因为在您解决了诺言后,返回的响应主体在.then()
块中进行了处理。
axios
.get('data.json')
.then(response => console.log(response.data))