在Ubuntu上使用Node.js實現跨域請求,通常會用到http
或express
這樣的庫來創建服務器,并通過設置響應頭來允許跨域。以下是使用這兩種方法的示例:
const http = require('http');
const server = http.createServer((req, res) => {
// 設置允許跨域的頭部
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);
res.end();
return;
}
// 響應請求
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
node your-server-file.js
mkdir my-express-app
cd my-express-app
npm init -y
npm install express
const express = require('express');
const app = express();
// 允許所有域名進行跨域訪問
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
// 處理GET請求
app.get('/', (req, res) => {
res.send('Hello World!');
});
// 處理POST請求
app.post('/data', (req, res) => {
res.json({ message: 'Data received' });
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
node your-express-app-file.js
在這兩個例子中,我們都設置了Access-Control-Allow-Origin
頭部來允許跨域請求。你可以將其設置為特定的域名,而不是使用通配符*
,以增加安全性。例如:
res.setHeader('Access-Control-Allow-Origin', 'http://example.com');
此外,如果你的API需要處理復雜的跨域請求(例如,帶有自定義頭或使用PUT、DELETE等方法的請求),你可能需要使用像cors
這樣的中間件來簡化配置。
安裝cors
中間件:
npm install cors
在Express應用中使用cors
:
const cors = require('cors');
app.use(cors());
這樣就可以更靈活地控制跨域請求的策略。