axios_设置withCredentials:true的情况下的跨域问题的解决办法

发布时间 2023-10-20 13:52:03作者: Steperouge
  • 在项目中的请求设置了withCredentials:true之后, 后端在设置Access-Control-Allow-Origin:*的情况下浏览器依然报跨域错误
  • https://blog.csdn.net/HermitSun/article/details/100797223这篇博文里了解到
    • withCredentials的情况下,后端要设置Access-Control-Allow-Origin为你的源地址,例如http://localhost:8080,不能是*,而且还要设置header(‘Access-Control-Allow-Credentials: true’);
  • 后端使用的是nodejs的cors来处理跨域, 配置如下
const whitelist = ['http://127.0.0.1:8080']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  },
  credentials: true
}
app.use(cors(corsOptions))
  • 如上配置后, 成功处理跨域