skr*_*skr 3 javascript vue.js axios
我正在尝试从我的 firebase 后端加载数据,但收到此错误
Uncaught (in promise) TypeError: response.json is not a function
Run Code Online (Sandbox Code Playgroud)
我的代码如下:
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 ');
}
});
};
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试response.data而不是response.json它有效并成功加载数据,所以我很好奇有什么区别以及为什么第一个不起作用。
由于 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: {}
}
Run Code Online (Sandbox Code Playgroud)
使用 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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26892 次 |
| 最近记录: |