[eggjs/egg]【求助篇】关于设置Cookie问题

2025-10-27 956 views
7
What happens?

get请求可以正常的设置Cookie,post请求似乎被拦截掉了。找了很久和搜了很多文章还是没有解决问题,所以来社区求助大家的帮助 谢谢?

错误信息

Access to XMLHttpRequest at 'http://127.0.0.1:7001/signIn' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

在get请求里面我设置 Access-Control-Allow-Credentials 可以解决问题,但是在POST似乎还没走到方法里面就已经拦截了

ctx.set('Access-Control-Allow-Credentials', 'true');
Axios
const client = axios.create({
  baseURL: process.env.VUE_APP_API,
  timeout: 1000 * 30,
  headers: {
  },
  withCredentials: true,
})
Config
  config.security = {
    domainWhiteList: [ 'http://localhost:8080', 'http://127.0.0.1:8080', 'http://127.0.0.1', 'http://www.cookie123456.com' ],
    csrf: {
      enable: false,
    },
  };
  exports.cors = {
    origin: 'http://127.0.0.1:8080',
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
    credentials: true,
  };

cors origin  设置过 * or http://127.0.0.1:8080 都无法通过,但是利用工具发送请求是正常的

浏览器发送请求

image

工具发送请求

image

最小可复现仓库

仓库地址:https://github.com/xiaotiandada/cli-ant-temp

复现步骤,错误日志以及相关配置 启动项目

项目是分离的

前端为 template/vue3 后端为 template/egg-temp

# front end
yarn serve

# backend
npm run dev

调用接口的按钮都在这里, Signin为Post, add remove为Get。

image

相关环境信息
  • 操作系统: Mac

  • Node 版本: v14.12.0

  • Egg 版本

    "egg": "^2.6.1",
    "egg-cors": "^2.2.3",

回答

7

错误信息不是写的明明白白么?

Access to XMLHttpRequest at 'http://127.0.0.1:7001/signIn' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy

跨域问题,可以不要改 domainWhiteList,直接改 origin 配置,看下 egg-cors 的 README

6

错误信息不是写的明明白白么?

谢谢回复 但是 origin 已经改过了

exports.cors = {
    origin: 'http://127.0.0.1:8080',
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
    credentials: true,
  };
7

可以自行跟下 egg-cors 那段源码看看哪一步没走下去。

8

image

刚修改过这个

5

可以自行跟下 egg-cors 那段源码看看哪一步没走下去。

我试试

4

image

刚修改过这个

。。。 可以去 MDN 看下 CORS 跨域的相关知识下,你这个是改自己浏览器的。。。

4

image 刚修改过这个

。。。 可以去 MDN 看下 CORS 跨域的相关知识下,你这个是改自己浏览器的。。。

? 社区群友提的修改建议 我试试?

6

可以自行跟下 egg-cors 那段源码看看哪一步没走下去。

设置 ctx.set('Access-Control-Allow-Credentials', 'true'); 放Cors里面居然就可以了 看流程的时候突发奇想。。

请教一下这是为啥 ?

image

get请求我是放在自己写的方法里面的 image

post请求也是放里面 但是设置不上 image

结果

image

5

已解决

一切都是因为粗心!!!

在排查cors中间价源码的时候,log app.config.cors.originundefined

说明config里面配置有问题

image

// {app_root}/config/config.default.js
exports.cors = {
  // {string|Function} origin: '*',
  // {string|Array} allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
};

在 // config.default.ts

config.cors = {
    ...
  };

谢谢大佬解决 辛苦了 @atian25

6

其实文档都写了的,看 run/application_config.json 可以看到配置合并情况

3

application_config

又学到了