fetch的局限性
2018-11-04 本文已影响13人
星月西
1. 发请求需要自己encode请求体
- 出于兼容性考虑,大部分项目发送POST请求时要使用aplication/x-www-form-urlencoded这种Content-Type,而且需要encode请求体
fetch('/api/add', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: Object.keys(data).map(key => {
return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
}).join('&')
});
- POST一个JSON到服务端
fetch('/api/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify(data)
});
2. fetch默认不会带上cookie
用fetch发送普通POST请求,可能会得到401 Unauthorized结果,fetch默认不会带上cookie
fetch('/api/add', {
method: 'POST',
credentials: 'include'
});
3. 错误处理复杂
fetch只有遇到网络错误时才会reject这个promise,比如用户断网或请求地址域名无法解析等,只要服务器能返回HTTP响应,promise一定是resolved状态
fetch('/red.json')
.then(res => res.json()) // 调用json失败导致的错误
.then(json => console.log(json))
.catch(err => {
console.log(err);
});
这里请求了一个不存在的文件red.json,最后报错为SyntaxError: Unexpected token < in JSON at position 0,可以看到请求本身并没有报错,是在调用json方法的过程中报错导致的。
判断fetch请求是否成功,需要使用response.ok字段。