关于fetch的使用
ckinmind opened this issue · 1 comments
ckinmind commented
问题:
- 如何使用fetch
ckinmind commented
- jQuery中ajax的使用如下
$.ajax({
url: 'https://hacker-news.firebaseio.com/v0/jobstories.json',
method: 'GET'
}).done(data => {
/** 备注这里的url只是测试用的,这个是之前hackernews的api,
* 这里只是确保接口是通的,至于数据还是自己mock
*/
let weight = Math.floor(200 + Math.random()*50);
dispatch(actions.donePickApple(weight));
}).fail(xhr => {
dispatch(actions.failPickApple(xhr.responseText));
})
- fetch 测试
fetch('https://hacker-news.firebaseio.com/v0/jobstories.json')
.then(response => {
console.log(response.status);
console.log(response);
console.log(response.json())
}).catch(e => {
console.log('something wrong');
});
测试的发现,如果请求url错误,catch并没有捕捉到错误,而是需要在then里通过response.status来判断返回状态,而jq的ajax可以通过fail方法来处理请求失败的情况
- 打印response的结果
/** 错误返回的responese */
{
body: ReadableStream,
bodyUsed:true,
headers: Headers,
ok: false,
status: 401,
statusText: "Unauthorized",
type: "cors",
url: "https://hacker-news.firebaseio.com/v0/jobstories123.json'"
...
}
/** 正确返回的responese */
{
body: ReadableStream,
bodyUsed:true,
headers: Headers,
ok: true,
status: 200,
statusText: "OK",
type: "cors",
url: "https://hacker-news.firebaseio.com/v0/jobstories.json'"
...
}