• 【前端开发】跨域请求如何携带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"
  • 相关阅读:
    HDU 4825 Xor Sum
    Linux下使用Crontab定时执行脚本
    HDU 4824 Disk Schedule
    Educational Codeforces Round 26 D. Round Subset 动态规划
    POJ 1833 排列
    HDU 1716 全排列
    HDU 1027 全排列
    Educational Codeforces Round 26 A C 之Python
    ACM输入输出之python
    标准C程序设计七---102
  • 原文地址:https://www.cnblogs.com/xiaohuizhang/p/16050207.html
Copyright © 2020-2023  润新知