美文网首页
egg.js 跨域 设置cookie

egg.js 跨域 设置cookie

作者: IamaStupid | 来源:发表于2021-04-06 17:59 被阅读0次

情形: egg.js 做后端接口, jQuery做前端请求。
设想:调用user/login接口后,后端设置cookie,然后前端每次请求都会自动带上cookie。
然而现实是后面的请求在控制台中,根本没有cookie;而且后端打印后面的接口也是没有cookie的。

后端跨域设置见:https://www.jianshu.com/p/202d760758d2

解决办法:
后端设置cookie:

                  // 登录验证成功后
                  ctx.cookies.set("username", param.name, {
                        maxAge: 1000 * 3600 * 24 * 7, // 有效期一天 * 7
                        httpOnly: true,
                        overwrite: true,//设置 key 相同的键值对如何处理
                        signed: true,//签名
                        encrypt: true, // 加密传输
                    });
                    ctx.cookies.set("userid", (jsonData[i].id + ''), {
                        maxAge: 1000 * 3600 * 24 * 7, // 有效期一天 * 7
                        httpOnly: true,
                        overwrite: true,//设置 key 相同的键值对如何处理
                        signed: true,//签名
                        encrypt: true, // 加密传输
                    });

前端ajax接口(login接口,后续的接口)都加上withCredentials:
xhrFields: {
withCredentials: true
},
crossDomain: true,

window.$.ajax({
        type: 'POST',
        url: config.apiServeUrl + '/user/login',
        data: JSON.stringify(obj),
        contentType: 'application/json;charset=utf-8',
        dataType: 'json',
        timeout: config.ajaxTimeout,
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        success: function(res) {
          alert(res.code + res.msg)
        },
        error: function(err) {
          console.log(err)
        }
      })
    }
image.png

ajax设置后,已经有cookie了。

egg.js controller中其他接口中获取浏览器带过来的cookie:

let cookie = ctx.cookies.get('userid', {
      encrypt: true
    })
console.log('cookie:', cookie, ctx.cookies.get('username', {
      encrypt: true
}))
image.png

清除cookie直接使用null替换即可:

ctx.cookies.set("userid", null)

相关文章

  • egg.js 跨域 设置cookie

    情形: egg.js 做后端接口, jQuery做前端请求。设想:调用user/login接口后,后端设置cook...

  • 跨域设置cookie

    当时的需求 大致是:前后台交互,但两个的地址不一样。需要后台识别当前的用户,那么后台就需要设置一个session,...

  • cookie

    key 键 value 值 expires 过期时间 domain 主域,不可以跨主域设置cookie,不过可以通...

  • [头参数]06 - Cookie

    目录 测试Cookie的流程 过期时间 设置httpOnly 设置Secure 跨域问题 0. 概述 常用参数 m...

  • 跨域资源共享 CORS

    跨域解决办法 1、 对于不用发送cookie的请求来说,直接设置: 2、如果需要发送cookie,xhr请求需要设...

  • Set-Cookie后,Cookie丢失问题解决(跨域)

    问题 iframe跨域访问,服务端设置免登cookie(response.addHeader("Set-Cooki...

  • 带cookie的跨域1

    带cookie的跨域1 1、Access-Control-Allow-Origin:*解决不了带Cookie的跨域...

  • node跨域设置cookie

    在做vue+express 做项目。 想做一个免登陆功能,选择session方案。 服务器设置session 后,...

  • 跨域 img 设置 cookie

    从技术层面来讲,我们可以设置 标签需要带上cookie等凭据来向后端请求图片资源,后端检测凭据是否合法来决定是...

  • 2021-09-22-🌦🌦 cookie 为什么作为token

    现象: 后端配置了cores跨域,前端直接请求,没有通过代理,这样如果设置cookie,只能设置到, localh...

网友评论

      本文标题:egg.js 跨域 设置cookie

      本文链接:https://www.haomeiwen.com/subject/hycekltx.html