NodeJS 如何在使用Express服务React文件时处理跨域问题?

r7knjye2  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(86)

我希望有一个节点后端和一个React前端在同一台服务器上运行。
我有一个这样的快速设置:

const express = require("express");
const helmet = require("helmet")
const bodyParser = require("body-parser")
const http = require("http")
const cors = require("cors")
const { Worker, workerData } = require("worker_threads")
const fs = require("fs");

const port = 80
const app = express();
app.use(helmet());
app.use(cors());

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

const server = http.createServer(app);

app.get("/", async (req, res) => {
    res.sendFile(__dirname + "/test.html")
})

server.listen(port, () => {
    console.log("Server listening on port " + port)
})

字符串
...并且它在浏览器中正确显示“test.html”。尽管控制台显示:
Cross-Origin-Opener-Policy标头已被忽略,因为URL的来源不可信。它在最终响应或重定向中定义。请使用HTTPS协议传递响应。您也可以使用'localhost' origin代替。参见https://www.w3.org/TR/powerful-features/#potentially-trustworthy-origin和https://html.spec.whatwg.org/#the-cross-origin-opener-policy-header。
该页使用Origin-Agent-Cluster标头请求了以来源为关键字的代理群集,但无法以来源为关键字,因为源“http://xxxxxxxx”以前已放置在以站点为关键字的代理群集中。更新您的头文件,以统一地请求源上所有页面的源键控。
但是当我切换到尝试像这样提供React构建文件夹时:

const express = require("express");
const helmet = require("helmet")
const bodyParser = require("body-parser")
const http = require("http")
const cors = require("cors")
const { Worker, workerData } = require("worker_threads")
const fs = require("fs");

const port = 80
const app = express();
app.use(helmet());
app.use(cors());

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

// ** adding this **

app.use(express.static("build"))

//**

const server = http.createServer(app);

// ** and changing this **

app.get("/", async (req, res) => {
    res.sendFile(__dirname + "/build/index.html")
})

// **

server.listen(port, () => {
    console.log("Server listening on port " + port)
})


React页面未加载。似乎问题是从各自的文件夹中加载js和css?我在想“express.static()”在这里也有帮助,但我显然错了...
会很感激任何提示,以帮助我解决这个问题!
下面是console返回的内容:
Cross-Origin-Opener-Policy标头已被忽略,因为URL的来源不可信。它在最终响应或重定向中定义。请使用HTTPS协议传递响应。您也可以使用'localhost' origin代替。请参阅https://www.w3.org/TR/powerful-features/#potentially-trustworthy-origin和https://html.spec.whatwg.org/#the-cross-origin-opener-policy-header。xxxxxxxxx/:1该页使用Origin-Agent-Cluster标头请求了以来源为关键字的代理群集,但无法以来源为关键字,因为来源“http://xxxxxxxxxx”以前已放置在以站点为关键字的代理群集中。更新您的头文件,以统一地请求源上所有页面的源键控。xxxxxxxxxxxx/:1获取https://xxxxxxxxxx/static/css/main.073c9b0a.css net::ERR_CONNECTION_CLOSED xxxxxxxxxx/:1获取https://xxxxxxxx/static/js/main.d36b2a27.js net::ERR_CONNECTION_CLOSED

4urapxun

4urapxun1#

  • 回答这个问题,以便它可以帮助其他人。* 最有可能的是,helmet()导致了这个安全错误;立即删 debugging 误:将helmet()替换为helmet({ contentSecurityPolicy: false, }),但这可能会导致安全问题。要了解有关contentSecurityPolicy的更多信息,请访问此链接

注意:如果它仍然表现相同,尝试删除/重置您的浏览器设置/存储

相关问题