本文共 1509 字,大约阅读时间需要 5 分钟。
一、问题1
【报错信息】:
from origin 'https://10.4.23.5:8080' has been blocked by CORS policy: 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
解释:这个报错包含了两个非常重要的信息
- 跨域访问中响应头的Access-Control-Allow-Origin字段不可以为通配符*
- 这个信任模式可以而请求端的withCredentials属性来控制
【问题的出现】:
有两个条件:
- 客户端A访问服务器B,返回的页面中要访问服务器C,从C返回的响应包头部中的Access-Control-Allow-Origin字段是*
- 服务器B在返回给A的页面中,把axios.defaults.withCredentials = true(如下是一个典型axios封装的例子)
import axios from 'axios'//基础设置axios.defaults.baseURL = 'https://10.4.23.5'axios.defaults.tiemout = 10000// 罪魁祸首,把它注释掉即可axios.defaults.withCredentials = trueaxios.defaults.headers['Content-type'] = 'application/json'// 请求拦截器axios.interceptors.request.use(config => { // return config}, error => { console.error('TODO:on error====>', error) return Promise.reject(error)})// 响应拦截器axios.interceptors.response.use(response => { return response.data}, error => { if (error.response) { return error.response } else { return Promise.reject(error) }})
其实所有的访问过程都是正常的,但是由于设置了axios.defaults.withCredentials = true,导致从服务器C返回的数据被浏览器认为不可信,所以报了以上的异常。
【解决 】
注释掉下面这一行即可
// axios.defaults.withCredentials = true
二、问题2
【报错信息】
Error: Network Error at createError (createError.js?2d83:16) at XMLHttpRequest.handleError (xhr.js?b50d:91)
【解决】
请参考:
转载地址:https://blog.csdn.net/menghaocheng/article/details/108716170 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!