前言
閱讀本文,你將學到:
1.學會`withCredentials`屬性; 2.學會`axios`配置`withCredentials`; 3.學會設置`Access-Control-Allow-Origin`屬性; 4.學會設置`Access-Control-Allow-Credentials`屬性; 5.學會解決跨域請求攜帶源站cookie的問題;
思路:
-
使用
express
搭建第一個服務A
(http://localhost:8000
),運行在8000
端口上; -
A
服務托管index.html
(用於在前端頁面發送網絡請求)文件; -
在
A
服務中寫一個處理請求的路由,加載index.html
頁面時,種下cookie
(這里種cookie
為了在請求B
服務時攜帶上); -
使用
express
搭建第二個服務B
(http://localhost:8003
),運行在8003
端口上; -
在
A
服務托管的index.html
頁面去請求B
服務,然后把cookie
傳過去;
教程
前端修改如下
// 修改跨域請求的代碼 crossButton.onclick = function () { axios({ withCredentials: true, // 前端增加設置這個 method: "get", url: "http://localhost:8003/anotherService", }).then((res) => { console.log(res); }); };
后端修改
// 在所有路由前增加,可以攔截所有請求 app.all("*", (req, res, next) => { res.header("Access-Control-Allow-Origin", "http://localhost:8000"); res.header("Access-Control-Allow-Credentials", "true"); next(); });
總結
前端請求時在request對象中配置"withCredentials": true; 服務端在response的header中配置"Access-Control-Allow-Origin", "http://xxx:${port}"; 服務端在response的header中配置"Access-Control-Allow-Credentials", "true"