JavaScript 请求方法
Axios(基于xhr的封装)
let url = 'https://example.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
let url = 'https://example.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
}
Fetch和Axios的区别
- IE 11兼容性:IE 11不支持 fetch API
- 不支持 progress:fetch 不支持 Progress 事件来追踪数据传输进度
- Promise Reject:fetch 不会在 HTTP 状态码为400或500时自动将 Promise 标记为 rejected
- 不支持 Timeout:fetch 不支持请求超时处理,要手动实现
- 不支持 JSONP:fetch 不支持 JSONP(JSON with Padding)请求,JSONP 通常用于跨域数据请求