前言
阅读本文,你将学到:
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"