【前端开发】跨域请求如何携带cookie
前言
阅读本文,你将学到:
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"
本文来自博客园,作者:JeckHui;
个人主页:前端实用站点推荐; 热榜资讯早读:热榜资讯-导航;
转载请注明原文链接:https://www.cnblogs.com/xiaohuizhang/p/16050207.html

浙公网安备 33010602011771号