【前端开发】跨域请求如何携带cookie

前言

阅读本文,你将学到:

1.学会`withCredentials`属性;
2.学会`axios`配置`withCredentials`;
3.学会设置`Access-Control-Allow-Origin`属性;
4.学会设置`Access-Control-Allow-Credentials`属性;
5.学会解决跨域请求携带源站cookie的问题;

思路:

  1. 使用express搭建第一个服务A(http://localhost:8000),运行在8000端口上;

  2. A服务托管index.html(用于在前端页面发送网络请求)文件;

  3. A服务中写一个处理请求的路由,加载index.html页面时,种下cookie(这里种cookie为了在请求B服务时携带上);

  4. 使用express搭建第二个服务B(http://localhost:8003),运行在8003端口上;

  5. 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"

 

posted @   JeckHui  阅读(1059)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示