Node.js 中 cors 依賴示例詳解
`cors` 是一個用于處理跨域資源共享(Cross - Origin Resource Sharing,CORS)問題的 Node.js 中間件,在前后端分離開發(fā)的項(xiàng)目中經(jīng)常會用到。
一、跨域問題概述
在瀏覽器中,出于安全考慮,遵循同源策略,即瀏覽器只允許訪問同源(協(xié)議、域名、端口都相同)的資源。當(dāng)瀏覽器向不同源的服務(wù)器發(fā)起請求時,就會受到瀏覽器的跨域限制,導(dǎo)致請求被阻止。CORS 是一種現(xiàn)代的跨域解決方案,允許服務(wù)器在響應(yīng)頭中設(shè)置一些字段,告訴瀏覽器該請求是被允許的。
1. 安裝 `cors`
# 使用 npm 安裝 npm install cors
2. 基本使用
將 `cors` 中間件應(yīng)用到整個 Express 應(yīng)用,這意味著所有路由都允許跨域請求。當(dāng)客戶端(如瀏覽器)發(fā)起對 `/data` 路由的請求時,服務(wù)器會在響應(yīng)頭中添加必要的 CORS 相關(guān)字段,從而允許跨域訪問。
const express = require("express");
const cors = require("cors");
const app = express();
// 使用 cors 中間件
app.use(cors());
app.get("/data", (req, res) => {
res.json({ message: "This is some data from the server" });
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});二、配置選項(xiàng)
`cors` 中間件提供了多種配置選項(xiàng),以滿足不同的跨域需求。
1. `origin`
用于指定允許跨域請求的源(origin)??梢允且粋€字符串、一個數(shù)組,或者是一個函數(shù)。
// 允許單個源
const corsOptions = {
origin: "http://example.com",
};
app.use(cors(corsOptions));
// 允許多個源
const corsOptionsMultiple = {
origin: ["http://example1.com", "http://example2.com"],
};
app.use(cors(corsOptionsMultiple));
// 使用函數(shù)動態(tài)配置 origin
const corsOptionsFunction = {
origin: (origin, callback) => {
const allowedOrigins = ["http://example.com", "http://test.com"];
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
};
app.use(cors(corsOptionsFunction));2. `methods`
用于指定允許的 HTTP 請求方法,默認(rèn)值為 `'GET,HEAD,PUT,PATCH,POST,DELETE'`。
const corsOptionsMethods = {
methods: "GET,POST",
};
app.use(cors(corsOptionsMethods));3. `allowedHeaders`
用于指定允許的請求頭,默認(rèn)情況下,瀏覽器會自動處理一些常見的請求頭。如果需要自定義請求頭,可以使用該選項(xiàng)。
const corsOptionsHeaders = {
allowedHeaders: "Content-Type,Authorization",
};
app.use(cors(corsOptionsHeaders));4. `exposedHeaders`
用于指定允許客戶端訪問的響應(yīng)頭。默認(rèn)情況下,瀏覽器只能訪問一些簡單的響應(yīng)頭,通過該選項(xiàng)可以暴露更多的響應(yīng)頭給客戶端。
const corsOptionsExposed = {
exposedHeaders: "X-Custom-Header",
};
app.use(cors(corsOptionsExposed));5. `credentials`
一個布爾值,指示是否允許客戶端在跨域請求中攜帶憑證(如 cookies、HTTP 認(rèn)證等)。默認(rèn)值為 `false`。
const corsOptionsCredentials = {
credentials: true,
};
app.use(cors(corsOptionsCredentials));6. 針對特定路由使用 `cors`
除了將 `cors` 應(yīng)用到整個應(yīng)用,還可以針對特定的路由使用 `cors` 中間件。
const express = require("express");
const cors = require("cors");
const app = express();
const corsOptions = {
origin: "http://example.com",
};
// 只允許特定路由跨域
app.get("/data", cors(corsOptions), (req, res) => {
res.json({ message: "This is some data from the server" });
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});到此這篇關(guān)于Node.js 中 cors 依賴詳解的文章就介紹到這了,更多相關(guān)Node.js cors 依賴內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
nodeJS(express4.x)+vue(vue-cli)構(gòu)建前后端分離實(shí)例(帶跨域)
這篇文章主要介紹了nodeJS(express4.x)+vue(vue-cli)構(gòu)建前后端分離實(shí)例(帶跨域) ,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
詳解基于Node.js的微信JS-SDK后端接口實(shí)現(xiàn)代碼
本篇文章主要介紹了詳解基于Node.js的微信JS-SDK后端接口實(shí)現(xiàn)代碼,具有一定的參考價值,有興趣的可以了解一下2017-07-07
windows系統(tǒng)下安裝yarn的詳細(xì)教程
yarn是一個新的JS包管理工具,它的出現(xiàn)是為了彌補(bǔ)npm的一些缺陷,下面這篇文章主要給大家介紹了關(guān)于windows系統(tǒng)下安裝yarn的詳細(xì)教程,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
如何解決安裝websocket還是報錯Cannot find module'ws&apos
這篇文章主要介紹了如何解決安裝websocket還是報Cannot find module'ws'問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02

