Fetch请求

Fetch请求

  • 概述
    • 对比
    • Fetch详解
      • 兼容性
        • options
      • 常见错误

概述

开发过程中向服务端发送请求常用的三种方式

方式 形式
XMLHttpRequest (XHR) 浏览器的原生API
Fetch 浏览器的原生API
AJAX【jQuery】 封装了XHR

对比

  • XHR
var xhr;
//浏览器兼容性差,需要手动匹配
if (window.XMLHttpRequest) {  // Mozilla, Safari...
   xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
   try {
     xhr = new ActiveXObject('Msxml2.XMLHTTP');
   } catch (e) {
     try {
       xhr = new ActiveXObject('Microsoft.XMLHTTP');
     } catch (e) {}
   }
}
if (xhr) {
   xhr.onreadystatechange = onReadyStateChange;
   xhr.open('POST', '/api', true);
   // 设置 Content-Type 为 application/x-www-form-urlencoded
   // 以表单的形式传递数据
   xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
   xhr.send('username=admin&password=root');
}

// onreadystatechange 方法
function onReadyStateChange() {
   // 该函数会被调用四次
   //回调折磨
   console.log(xhr.readyState);
   if (xhr.readyState === 4) {
      // everything is good, the response is received
      if (xhr.status === 200) {
         console.log(xhr.responseText);
      } else {
         console.log('There was a problem with the request.');
      }
   } else {
      // still not ready
      console.log('still not ready...');
   }
}

从上边的代码可以看出,XHR 是一个非常粗糙的API,不符合关注分离(Separation of Concerns)的原则,配置和调用方式非常混乱,前端程序员们不仅要做各个浏览器的兼容性,还饱受回调地狱的折磨,这显然不是一个好的选择。

  • AJAX
	$.ajax({
	    method: 'POST',
	    url: '/api',
	    data: { username: 'admin', password: 'root' }
	}).done(function(msg) {
		alert( 'Data Saved: ' + msg );
	});

AJAX在兼容性和易用性方面有了很大的提高,同时可以使用jsonp跨域。但是回调问题依然存在。

  • Fetch
fetch(...).then(fun2)
          .then(fun3) //各依赖有序执行
          .catch(fun);

回调相对AJAX好了许多。

Fetch详解

兼容性

Fetch API 是基于 Promise 设计,旧浏览器不支持 Promise,需要使用 pollyfill es6-promise

options

属性 解释 默认
method(String) 请求方法 GET
body(String) 请求参数
headers(Object) 请求头 {}
credentials(String) cookie管理 omit:忽略,默认,不带cookie;same-origin:同源请求带cookie;include:无论跨域还是同源请求都会带cookie

常见错误

  1. 允许域未设置
    fetch请求错误
    通常解决方法
	//最简单的设置跨域 *;有时不允许设置为*,需添加具体域名
	res.setHeader('Access-Control-Allow-Origin', '*'); 
  1. Content-Type问题
    fetch请求错误
    通常解决方法
	res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  1. cookie携带问题
    fetch请求错误
    通常解决方法
	//告诉客户端可以在HTTP请求中带上Cookie
	res.setHeader('Access-Control-Allow-Credentials', true);
	fetch(url,{
	    credentails:'include',   // 允许允许传递 cookie
	})
  1. *的问题
    fetch请求错误
    通常解决方法
    String origin = "";
	res.setHeader('Access-Control-Allow-Origin', origin);
	//注意这里不能使用 *// origin 是你需要请求跨域资源的来源地址
// 如上面错误就可以是 http://127.0.0.1:8082
  1. mode 设置问题
    fetch请求错误
    在 network 的相应请求中,有数据返回来,请求可以看到但是就是得不到数据,fetch 无反应这时候在控制台 console 上会出来这样错误

    通常解决方法

   fetch(url,{
    	mode:'cors',  //将 no-cors 改为 cors
	});
  1. 后端返回数据格式问题
    fetch请求错误
    需要协调,将格式转化一下。

你可能感兴趣的:(java)