Axios Post 请求不包含凭证,尽管凭证存在

问题描述 投票:0回答:1

Cookies 没有通过我的 axios POST 请求在 React 中传递。我的前端使用此代码发出发布请求

// (localhost:5173)
const response = await axios.post(
      `api/addData`,
      body,
      { withCredentials: true }
    )

调用以下 Node.js Azure 函数

// (localhost:3000)
app.http("addData", {
  methods: ["GET", "POST"],
  authLevel: "anonymous",
  route: "addData",
  handler: async (request, context) => {
    const cookies = request.headers.get("cookie")
    context.log("cookies are ", cookies)
    return {
      status: 200,
      headers: {
        "Access-Control-Allow-Credentials": true,
      },
      body: "Data Added",
    }

这会出现 CORS 错误

从源“http://localhost:5173”访问“http://localhost:3000/api/addData”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:该值响应中“Access-Control-Allow-Credentials”标头的值为“”,当请求的凭据模式为“include”时,该值必须为“true”。 XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

这感觉很奇怪,因为

  1. 如果我向同一端点发出 GET 请求,则包含 cookie(并且没有 CORS 问题)

    const response = await axios.get(
          `api/addData`,
          { withCredentials: true }
        )
    

    日志显示

    cookies are <cookie-values>
    这是我想要的,并且

  2. 我的

    local.settings.json
    文件包括

      "Host": {
        "CORS": "http://localhost:5173"
      }
    

如何使 post 请求包含 cookie?

post cookies axios credentials
1个回答
0
投票

您的 POST 请求并不简单,因此需要预检

OPTIONS
请求。对该预检请求的响应没有必要的
Access-Control-Allow-Credentials: true
标头,因此会出现错误消息。

要在本地支持 CORS 预检请求,您需要包含

CORSCredentials
属性

"Host": {
  "CORS": "http://localhost:5173",
  "CORSCredentials": true
}

参考:本地设置文件

设置 描述
CORSCredentials
设置为
true
时,允许
withCredentials
请求。
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.