在 CentOS 系統上配置 Node.js 應用以支持跨域資源共享(CORS),可以通過多種方式實現。以下是幾種常見的方法:
cors
中間件安裝 Node.js 和 npm: 確保你已經在 CentOS 上安裝了 Node.js 和 npm。如果沒有安裝,可以參考以下步驟:
sudo yum install -y nodejs npm
創建一個新的 Node.js 項目: 創建一個新的目錄并進入該目錄,然后初始化一個新的 Node.js 項目。
mkdir my-node-app
cd my-node-app
npm init -y
安裝 Express 和 cors 中間件: 使用 npm 安裝 Express 和 cors 中間件。
npm install express cors
創建一個簡單的 Express 應用:
創建一個 index.js
文件,并添加以下代碼:
const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;
// 使用 cors 中間件
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
運行應用: 在終端中運行你的應用。
node index.js
現在,你的應用應該在 http://localhost:3000
上運行,并且支持 CORS。
如果你不想使用中間件,也可以手動設置 CORS 頭。以下是一個示例:
const http = require('http');
const server = http.createServer((req, res) => {
// 設置 CORS 頭
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
res.writeHead(200);
return res.end();
}
res.end('Hello World!');
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
如果你希望通過 Nginx 反向代理來處理 CORS,可以按照以下步驟進行配置:
安裝 Nginx: 如果你還沒有安裝 Nginx,可以使用以下命令安裝:
sudo yum install nginx
配置 Nginx:
編輯 Nginx 配置文件(通常位于 /etc/nginx/nginx.conf
或 /etc/nginx/conf.d/default.conf
),添加以下內容:
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization' always;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain charset=UTF-8';
return 200;
}
}
}
重啟 Nginx: 保存配置文件并重啟 Nginx。
sudo systemctl restart nginx
現在,你的 Node.js 應用應該可以通過 Nginx 反向代理訪問,并且支持 CORS。
選擇適合你需求的方法進行配置即可。