关于Axios中写了axios.defaults.withCredentials = true,携带Session还是有问题


前言


这次项目登录的时候利用axios传输的时候发现后台接收的到sessionID但是返回前台的时候cookie却没有sessionID,
网上大多数都是axios.defaults.withCredentials = true,但是没用,解决了一下午,终于找到了答案

一、修改之前

1.登录

代码如下(示例):

 axios({
        widthCredentials: true,
          method: 'post',
          url: "http://location:8080/api/guojia/all/login",
          data: _this.form
      }).then(res => {
          console.log(res)
          if (res.data != null && res.data != "") {
              localStorage.setItem("position", res.data.position.pname)
              sessionStorage.setItem("tabs", "");
              location.href = "../../index.html"
          } else {
              this.$message.error('账号或者密码错误');
          }
      })

2.登录之后读取

代码如下(示例):

 axios({
        method: 'get',
        url: "http://127.0.0.1:8080/api/guojia/all/getUser",
        widthCredentials: true
      }).then(res => {
        _this.User = res.data
        $(".allpage").hide();
        showsItem = _this.User.position.operatingList;
        pageInit()
        $("#hhhh").load("index2.html")
      })

照网上大多数的方法,我已经加上了axios.defaults.withCredentials = true,但是还是没有解决


二、解决方案

不知道大家注意到没有我登录的URL和读取的URL有什么不同,在登录的时候我写的是http://location:8080,看群友说,有时候location返回时前端无法保存到cookie,这是错误一,错误二是读取的时候我写的是http://127.0.0.1:8080,这就导致了两次访问的地址不一样,当然取不到SessionID

三、修改之后

1.登录

代码如下(示例):

 axios({
        widthCredentials: true,
          method: 'post',
          url: "http://127.0.0.1:8080/api/guojia/all/login",
          data: _this.form
      }).then(res => {
          console.log(res)
          if (res.data != null && res.data != "") {
              localStorage.setItem("position", res.data.position.pname)
              sessionStorage.setItem("tabs", "");
              location.href = "../../index.html"
          } else {
              this.$message.error('账号或者密码错误');
          }
      })

2.登录之后读取

代码如下(示例):

 axios({
        method: 'get',
        url: "http://127.0.0.1:8080/api/guojia/all/getUser",
        widthCredentials: true
      }).then(res => {
        _this.User = res.data
        $(".allpage").hide();
        showsItem = _this.User.position.operatingList;
        pageInit()
        $("#hhhh").load("index2.html")
      })

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值