使用fetch时遇到的问题 - pod4g/tool GitHub Wiki

一、fetch目前不能发送同步请求

https://segmentfault.com/q/1010000008030089/a-1020000008030285

二、fetch没有进度函数

三、fetch不能设置timeout

四、fetch带cookie

在CMS系统中,打log时,我想每次log的头部都带有本次操作的用户名,若没有用户名,则生成一个sessionID,这样方便以后我们看log。

所以就引出来,在每次请求时,都带cookie头

若每次fetch(或ajax请求)请求想要带上cookie,需要在前端设置: credentials: 'include’

fetch(API.authors.url,{ credentials: 'include’, method: 'GET', mode:'cors', headers: new Headers({ 'Content-Type': 'json' }) }) .then(response => response.json()) .then(result => {

})

在后端也需要加上:

res.header('Access-Control-Allow-Credentials', true)

但是若在后端设置的Access-Control-Allow-Origin为*,即任何域名都可以跨域访问,则在前端会报错:

Fetch API cannot load http://127.0.0.1:3000/authors. Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8080' is therefore not allowed access.

在后端把 Access-Control-Allow-Origin 改为 http://localhost:8080 即可。。

所以对于即想跨域又想带cookie的话,必须要这样做。。

fetch中的header如果带中文,则报错: Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid value