Fetch

参考文章:

MDN:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API

MDN: https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch

fetch-ie8 : https://github.com/camsong/fetch-ie8

fetch字段讲解:https://www.w3ctech.com/topic/854

fetch字段讲解: https://gold.xitu.io/entry/583684d4880741006c081fa6

传统 Ajax 已死,Fetch 永生 :https://github.com/camsong/blog/issues/2

重点看一下配置项里面各字段的含义

init 可选一个配置项对象,包括所有对请求的设置。可选的参数有:

  • method: 请求使用的方法,如 GETPOST。
  • headers: 请求的头信息,形式为 Headers 对象或 ByteString
  • body: 请求的 body 信息:可能是一个 BlobBufferSourceFormDataURLSearchParams 或者 USVString 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息。
  • mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
  • credentials: 请求的 credentials,如 omitsame-origin 或者 include。
  • cache:  请求的 cache 模式: defaultno-storereloadno-cacheforce-cache, or only-if-cached.

 

header中常用的选项是

'Accept': 期望接受的数据类型

如:'application/json'   

 

'Content-Type' :body的内容格式

'application/x-www-form-urlencoded;charset=utf-8';  

multipart/form-data

application/json

text/xml

 

属性

method 请求的方法POST/GET等
url 请求的地址
headers 请求头(可以是Headers对象,也可是JSON对象)
context 请求的上下文
referrer 指定请求源地址
mode 请求的模式(是跨域cors还是正常请求no-cors)
credentials 跨域请求时,是否携带cookie信息(omit跨域携带/same-origin同源携带)
redirect 重定向
integrity 一个散列值,用于检验请求资源的完整性MDN
cache 是否缓存这个请求

 

 

尝试跨域请求:

fetch ('http://localhost:8018/category/list.ajax',{

mode: 'cors',

credentials: 'include'

}).then(function (res){

if(res.ok) {

return res.json()

}

}).then(function (data){

console.log(data)

 

})

 

首先是浏览器的fetch 设置 mode为cors

然后服务器设置允许跨域访问

 

express

app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,PUT');

res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});

fetch的credentials枚举属性决定了cookies是否能跨域得到。这个属性与XHR的withCredentials标志相同,但是只有三个值,分别是"omit"(默认),"same-origin"以及"include"。

omit  是不带cookie   same-origin 是同源请求才带cookie   include可以保证跨域请求也带cookie。

 

mode属性用来决定是否允许跨域请求,以及哪些response属性可读。可选的mode属性值为same-originno-cors(默认)以及cors

posted @ 2017-01-07 16:04  杨博客  阅读(627)  评论(0编辑  收藏  举报