[英]Express.js CORS between servers
I have a small problem with the connection between my Expressjs API and the React client.我的 Expressjs API 和 React 客户端之间的连接有一个小问题。
Express API -> http://localhost:3001 React -> http://exampleip:3000 (both are on the same windows server) Express API -> http://localhost:3001 React -> http://exampleip:3000(都在同一个windows服务器上)
I added the package CORS and add the following code我添加了包 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);
});
If I fetch the data with the react app on the server where the code is located, I receive the data from the express api without problems.如果我在代码所在的服务器上使用 react 应用程序获取数据,我会毫无问题地从 express api 接收数据。
If I fetch the data with the ip from the react app on my local pc or on a citrix terminal session (windows) on the same network (but not on the same windows server), I receive the following errors.如果我从本地 PC 上的 react 应用程序或同一网络(但不在同一 Windows 服务器上)上的 citrix 终端会话(windows)上使用 ip 获取数据,则会收到以下错误。
i prefer to use this code it will help you我更喜欢使用这个代码它会帮助你
// 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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.