【问题标题】:No CORS error when making GET requests, but CORS error when making POST requests发出 GET 请求时没有 CORS 错误,但发出 POST 请求时出现 CORS 错误
【发布时间】:2022-01-06 22:53:10
【问题描述】:

我有一个与 React 应用交互的 Node/Express 服务器。

我需要发出 POST 和 GET 请求,问题是发出 POST 请求时出现 CORS 错误,通常:

Access to fetch at 'http://localhost:9000/testAPI' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我在服务器上的响应中指定了 Access-Control-Allow-Origin 标头,但我不确定是否也必须为 POST 请求设置此标头。如果我这样做,它应该指定什么域?

我也不愿意使用诸如 CORS 扩展或 npm 包之类的技巧。我想使用 CORS。

服务器端如下所示:

const express = require("express");
const router = express.Router();

router.get("/", (req, res, next) => {
    console.log(req.url);

    res.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
    res.send("API is working properly");
});

module.exports = router;

在 React 应用程序中,GET 请求看起来像这样(工作正常):

const res = await fetch('http://localhost:9000/testAPI');

console.log(res);

POST 请求如下所示(抛出 CORS 错误):

const res = await fetch('http://localhost:9000/testAPI', {
    method: 'POST',
    mode: 'cors',
    cache: 'no-cache',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ someData: "POST requests are working properly" })
});

我是否需要在 POST 请求中指定一些额外的标头或属性?还是我必须在服务器端修改一些东西?

如果我在上线时不会遇到这个问题,那么我不介意使用像 CORS 扩展这样的 hack。

【问题讨论】:

  • 设置 POST 请求的标头并使用相同的端口 localhost:9000 localhost:3000 是不同的来源
  • 我希望我做对了:const res = await fetch('http://localhost:9000/testAPI', { method: 'POST', mode: 'cors', cache: 'no-cache', headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:9000' }, body: JSON.stringify({ someData: "POST requests are working properly" }) });。很遗憾没有工作。如果你想让我做点别的事,请告诉我。
  • 试试'Access-Control-Allow-Origin': '*'
  • 没用。谢谢你
  • @LucianAnghel 首先:确保您阅读并理解developer.mozilla.org/en-US/docs/Web/HTTP/CORS

标签: node.js reactjs post get cors


【解决方案1】:

你可以使用这个包cors

// Install
npm install cors
yarn add cors
    // server.js 
    const express = require('express');
    const cors = require('cors');
    const app = express();
    
    // global middleware
    app.use(cors());
    // You can use route based middleware too
    router.post("/", cors(), (req, res, next) => {
     // process request & send response to client
    });


【讨论】:

    猜你喜欢
    • 2022-01-23
    • 2021-06-18
    • 2021-03-02
    • 2015-10-07
    • 2018-08-16
    • 2020-04-03
    • 2020-11-29
    • 2019-09-09
    相关资源
    最近更新 更多