React 解决fetch跨域请求时session失效

在解决fetch跨域请求接口的时候,通常都是让后台接口在返回头里添加json

//容许全部域名的脚本访问该资源
header("Access-Control-Allow-Origin: *");

image.png

确实这样是能够解决跨域请求的问题,可是若是咱们要在请求的时候添加session,那么这样设置就会出现问题了。
fetch添加Cookie验证的方法是设置credentials: 'include'跨域

fetch(url, {
        method: 'POST',
        body: JSON.stringify(params),
        mode: 'cors',
        //请求时添加Cookie
        credentials: 'include',
        headers: new Headers({
            'Accept': 'application/json',
            "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
        })
    })

设置好了以后,信心满满的发起请求。却发现网络请求报错了网络

A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3000' is therefore not allowed access

缘由是网络请求须要携带Cookie时Access-Control-Allow-Origin是不能设置为*的,这个时候应该要给Access-Control-Allow-Origin指定域名
image.pngsession

这样就能够达到跨域请求的同时传递Cookie的目的了app

  • 列表项目
相关文章
相关标签/搜索