Axios -跨域Cookie

vxf3dgd4  于 2022-11-05  发布在  iOS
关注(0)|答案(3)|浏览(122)

我有两个应用程序(后端和前端)在本地计算机上运行(前端- Vue应用程序在端口8080上,后端- Scala应用程序在端口9000上)
我试图发送请求到后端使用Axios与cookie,但它只工作,如果两者都运行在同一个域:

正在工作(API请求中存在cookie):

我的前端片段与请求:

const BASE_URL = appConfig.API_URL + '/api';
axios.defaults.withCredentials = true;
axios.get(BASE_URL + '/systems');

我认为CORS配置正确:

play.filters.cors {
  allowedOrigins = ["http://localhost:8080", "http://127.0.0.1:8080"]
  supportsCredentials = true
  allowedHttpMethods = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
}
mspsb9vt

mspsb9vt1#

请在后端尝试以下操作:

const allowedOrigins = ['localhost',"http://localhost:8080", "http://127.0.0.1:8080","http://localhost:8080/"];
var corsOptions = {
  origin: function (origin, callback) {
    if (allowedOrigins.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
      console.log("------")
      console.log("origin",origin)
    }
  },
  credentials: true,
}
9w11ddsr

9w11ddsr2#

您需要在响应中设置标头:

Access-Control-Allow-Headers: Set-Cookie

在node.js上的express中,它是这样的:

res.setHeader('Access-Control-Allow-Headers', 'Set-Cookie')
ou6hu8tu

ou6hu8tu3#

不同的端口被认为是跨域的,所以这可能不是CORS设置的问题,因为在第一个示例中,跨域请求是有效的。

相关问题