一、Node.js 跨域問題
隨着前後端分離的不斷深入以及微服務架構的普及,前端發起跨域請求是必不可少的。而 Node.js 作為一種服務器端語言,也需要面對跨域問題。
跨域請求,簡單來說就是一個頁面的腳本在發送 XMLHttpRequest (AJAX)請求時,請求的 URL 與該頁面所搭載的服務器不在同一域下。
Node.js 默認情況下是無法處理跨域請求的,一般來說我們可以通過一些中間件去實現跨域請求功能。
二、Node.js 構建網頁
在 Node.js 中,我們可以使用模板引擎來渲染 HTML 頁面,讓 Node.js 具備構建網頁的功能。其中,我們比較常用的兩個模板引擎是 EJS 和 Pug。在這裡,我們以 EJS 為例。
// app.js
const express = require('express');
const path = require('path');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index', { title: 'Node.js 跨域請求' });
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
// views/index.ejs
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= title %></h1>
</body>
</html>
三、Node.js 跨域請求
1、nodejs 跨域 cors
CORS(跨域資源共享)是一種機制,它使用類似於 JSONP 的方式允許跨域訪問,需要在服務器響應頭中設置 Access-Control-Allow-Origin,表示允許哪些域的請求跨域。
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/', (req, res) => {
res.send('Hello world!');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
2、nodejs 跨域 直接轉發
有時候,我們需要直接將請求轉發到另一個域名下的服務器,這時候可以使用 http-proxy-middleware 中間件。
const express = require('express');
const proxy = require('http-proxy-middleware');
const app = express();
app.use('/api', proxy({ target: 'http://localhost:8080', changeOrigin: true }));
app.listen(3000, () => {
console.log('Server started on port 3000');
});
四、Node.js 解決跨域問題
1、nodejs 跨域問題 cors
除了直接使用 cors 中間件以外,還可以手動設置響應頭來實現跨域請求。在這裡,我們自行編寫一個中間件來實現該功能。
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.get('/', (req, res) => {
res.send('Hello world!');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
2、nodejs 跨域問題 nginx
在生產環境中,我們通常使用反向代理服務器(如 Nginx)來解決跨域問題,Nginx 已經自帶了實現 CORS 的功能,只需要簡單的配置即可。
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
location /api/ {
add_header 'Access-Control-Allow-Origin' '*';
proxy_pass http://localhost:3000;
}
}
五、Node 跨域問題解決方案總結
通過以上的講解,我們了解了 Node.js 跨域問題以及解決方案。需要注意的是,不同的方案適用於不同的場景,我們需要根據實際情況選擇最適合自己的方法。同時,還需要注意安全性問題,避免出現安全漏洞。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/301589.html