在 Linux 系统中,Node.js 处理跨域问题的方法与在其他操作系统中的方法相同。这里我们将介绍两种常用的方法来解决跨域问题:CORS(跨域资源共享)和代 理服务器。

方法一:CORS(跨域资源共享)
CORS 是一种跨域访问的机制,允许服务器通过设置 HTTP 响应头来指定哪些源(域名、协议和端口)可以访问其资源。要在 Node.js 中使用 CORS,你可以使用第三方库,如 cors。
cors 库:npm install corscors:const express = require('express');const cors = require('cors');const app = express();// 允许所有来源访问app.use(cors());// 或者,你可以指定允许访问的来源app.use(cors({ origin: 'http://example.com' }));// 你的路由和其他代码方法二:代 理服务器
代 理服务器是一种将请求转发到其他服务器的方法,可以用来绕过跨域限制。在 Node.js 中,你可以使用 http-proxy-middleware 库来创建一个代 理服务器。
http-proxy-middleware 库:npm install http-proxy-middlewarehttp-proxy-middleware:const express = require('express');const { createProxyMiddleware } = require('http-proxy-middleware');const app = express();app.use('/api', createProxyMiddleware({target: 'http://target-server.com',changeOrigin: true,}));// 你的路由和其他代码在这个例子中,所有以 /api 开头的请求都会被代 理到 http://target-server.com。
这两种方法都可以解决 Node.js 中的跨域问题。你可以根据自己的需求选择合适的方法。