Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于fetch的使用 #10

Open
ckinmind opened this issue Feb 9, 2017 · 1 comment
Open

关于fetch的使用 #10

ckinmind opened this issue Feb 9, 2017 · 1 comment

Comments

@ckinmind
Copy link
Owner

ckinmind commented Feb 9, 2017

问题:

  1. 如何使用fetch
@ckinmind
Copy link
Owner Author

ckinmind commented Feb 9, 2017

  1. 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));
            })
  1. 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方法来处理请求失败的情况

  1. 打印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'"
   ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant