【问题标题】:Express.js CORS between servers服务器之间的 Express.js CORS
【发布时间】:2021-12-18 17:06:29
【问题描述】:

我的 Expressjs API 和 React 客户端之间的连接有一个小问题。

Express API -> http://localhost:3001 反应 -> http://exampleip:3000 (两者都在同一个 Windows 服务器上)

我添加了包CORS并添加以下代码

const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());

... other code

app.use('/testdata', async function (req, res) {
    const data = await receiveData();
    res.send(data);
});

如果我在代码所在的服务器上使用 react 应用程序获取数据,我会毫无问题地从 express api 接收数据。

如果我从本地 pc 上的 react 应用程序或同一网络(但不在同一 windows 服务器上)上的 citrix 终端会话(windows)上使用 ip 获取数据,我会收到以下错误。

Console error Screenshot

Network error Screenshot

【问题讨论】:

  • 请使用tour 并阅读How to Ask。 Stack Overflow 用户喜欢看到的一件事是文本作为文本,而不是文本的屏幕截图。 How to Ask 中以粗体字提到了这一点,“请勿发布代码、数据、错误消息等的图像。 - 将文本复制或输入到问题中。”

标签: javascript node.js reactjs express cors


【解决方案1】:

我更喜欢使用此代码,它会对您有所帮助

// init application
const app = express();

// fix access to back-end
app.use((req, res, next) => {
  // Website you wish to allow to connect
  res.setHeader("Access-Control-Allow-Origin", process.env.FRONTEND_APP_HOST);

  // Request methods you wish to allow
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, OPTIONS, PUT, PATCH, DELETE"
  );

  // Request headers you wish to allow
  res.setHeader(
    "Access-Control-Allow-Headers",
    "X-Requested-With,content-type"
  );

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader("Access-Control-Allow-Credentials", true);

  // Pass to next layer of middleware
  next();
});

【讨论】:

    猜你喜欢
    • 2019-09-29
    • 1970-01-01
    • 2012-04-27
    • 2015-11-26
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多