fetch()

fetch方法的第一个参数可以是 URL 字符串,也可以是后文要讲到的Request对象实例。Fetch方法返回一个Promise对象,并将一个response对象传给回调函数。

response对象有一个ok属性,如果返回的状态码在200到299之间(即请求成功),这个属性为true,否则为false。因此,判断请求是否成功的代码可以写成下面这样。

  1. fetch('./api/some.json').then(function (response) {
  2. if (response.ok) {
  3. response.json().then(function (data) {
  4. console.log(data);
  5. });
  6. } else {
  7. console.log('请求失败,状态码为', response.status);
  8. }
  9. }, function(err) {
  10. console.log('出错:', err);
  11. });

response对象除了json方法,还包含了服务器 HTTP 回应的元数据。

  1. fetch('users.json').then(function(response) {
  2. console.log(response.headers.get('Content-Type'));
  3. console.log(response.headers.get('Date'));
  4. console.log(response.status);
  5. console.log(response.statusText);
  6. console.log(response.type);
  7. console.log(response.url);
  8. });

上面代码中,response对象有很多属性,其中的response.type属性比较特别,表示HTTP回应的类型,它有以下三个值。

  • basic:正常的同域请求
  • cors:CORS 机制下的跨域请求
  • opaque:非 CORS 机制下的跨域请求,这时无法读取返回的数据,也无法判断是否请求成功

如果需要在 CORS 机制下发出跨域请求,需要指明状态。

  1. fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'})
  2. .then(function(response) {
  3. return response.text();
  4. })
  5. .then(function(text) {
  6. console.log('Request successful', text);
  7. })
  8. .catch(function(error) {
  9. log('Request failed', error)
  10. });

除了指定模式,fetch 方法的第二个参数还可以用来配置其他值,比如指定 cookie 连同 HTTP 请求一起发出。

  1. fetch(url, {
  2. credentials: 'include'
  3. })

发出 POST 请求的写法如下。

  1. fetch('http://www.example.org/submit.php', {
  2. method: 'POST',
  3. headers: {
  4. 'Content-Type': 'application/x-www-form-urlencoded'
  5. },
  6. body: 'firstName=Nikhil&favColor=blue&password=easytoguess'
  7. }).then(function(res) {
  8. if (res.ok) {
  9. console.log('Perfect! Your settings are saved.');
  10. } else if (res.status == 401) {
  11. console.log('Oops! You are not authorized.');
  12. }
  13. }, function(e) {
  14. console.log('Error submitting form!');
  15. });