Axios请求报refused to set unsafe header cookie错误如何解决?
问题原因
"refused to set unsafe header cookie"错误是浏览器的安全限制导致:Cookie属于浏览器禁止前端代码手动修改的请求头字段,W3C的XMLHttpRequest规范明确禁止JS修改这类安全相关的请求头,任何手动设置Cookie请求头的操作都会被浏览器拦截。
另外你当前的代码还存在参数配置错误:credentials是fetch API的跨域凭据配置字段,Axios对应的配置字段为withCredentials。
解决步骤
- 第一步:移除headers中手动设置的
'Cookie': document.cookie配置,Cookie会由浏览器自动管理携带,无需手动设置 - 第二步:替换错误的
credentials配置为Axios对应的withCredentials配置:- 同域请求时设置
withCredentials: true,浏览器会自动携带当前域名下的所有Cookie - 跨域请求时除了前端设置
withCredentials: true,还需要后端配合完成CORS配置:- 响应头
Access-Control-Allow-Credentials必须设置为true - 响应头
Access-Control-Allow-Origin不能设置为通配符*,必须指定和前端一致的具体域名
- 响应头
- 同域请求时设置
修改后的代码示例
axios.get('https://localhost:44303/api/Home',{ headers:{ "Accept": "application/json", "Authorization": "Bearer " + localStorage.getItem("user"), "Cache-Control": "no-cache" // 移除手动设置的Cookie字段 }, withCredentials: true // 替换原错误的credentials配置 }).then(Response => this.games = Response.data);
内容的提问来源于stack exchange,提问作者mistake22
相关产品推荐
相关产品推荐

