【前端开发】跨域请求如何携带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"

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM