登录之后的请求会带登录用户信息,需要把登录时的cookie设置到之后的请求头里面。而跨域请求要想带上cookie,必须要在vue的main.js里加上axios.defaults.withCredentials = true。withCredentials 属性是一个Boolean类型,它指示了是否该使用类似cookies,authorization,headers(头部授权)或者TLS客户端证书这一类资格证书来创建一个跨站点访问控制(cross-site Access-Control)请求。
axios.defaults.withCredentials = true;//设置cross跨域 并设置访问权限 允许跨域携带cookie信息
但是前端这样设置之后发现报错了!
Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy: 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
原因是:前端设置withCredentials的情况下,后端要设置Access-Control-Allow-Origin为你的源地址,例如http://localhost:8080,不能是*,而且还要设置header(‘Access-Control-Allow-Credentials: true’);
另外,Access-Control-Allow-Origin设置为*,时cookie不会出现在http的请求头里,所以报错里说Access-Control-Allow-Origin不能是*。
本文地址:https://blog.csdn.net/xiaoyuer_2020/article/details/109000664