fetch和axios区别,摘自Stack Overflow网站答案
fetch 请求
let url = 'https://someurl.com'; let options = { method: 'POST', mode: 'cors', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8' }, body: JSON.stringify({ property_one: value_one, property_two: value_two }) }; let response = await fetch(url, options); let responseOK = response && response.ok; if (responseOK) { let data = await response.json(); // do something with data }
axios请求示例
let url = 'https://someurl.com';
let options = {
method: 'POST',
url: url,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
data: {
property_one: value_one,
property_two: value_two
}
};
let response = await axios(options);
let responseOK = response && response.status === 200 && response.statusText === 'OK';
if (responseOK) {
let data = await response.data;
// do something with data
}
原答案:
- Fetch's body = Axios' data
- Fetch's body has to be stringified, Axios' data contains the object
- Fetch has no url in request object, Axios has url in request object
- Fetch request function includes the url as parameter, Axios request function does not include the url as parameter.
- Fetch request is ok when response object contains the ok property, Axios request is ok when status is 200 and statusText is 'OK'
- To get the json object response: in fetch call the json() function on the response object, in Axios get data property of the response object.
自己理解答案:
fetch 中的body是axios的data项
fetch的请求体必须是字符串,axios是对象
fetch请求对象不包含URL,axios请求对象包含url
fetch方法包含url作为参数,axios不用;
当接收到一个代表错误的 HTTP 状态码时,从 fetch()返回的 Promise 不会被标记为 reject, 即使该 HTTP 响应的状态码是 404 或 500。相反,它会将 Promise 状态标记为 resolve (但是会将 resolve 的返回值的 ok 属性设置为 false ), 仅当网络故障时或请求被阻止时,才会标记为 reject。

浙公网安备 33010602011771号