Skip to content

【求助篇】关于设置Cookie问题 #4579

@xiaotiandada

Description

@xiaotiandada

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",

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions