【问题标题】:Superagent share session / cookie info with actual browserSuperagent 与实际浏览器共享会话/cookie 信息
【发布时间】:2026-02-10 14:40:01
【问题描述】:

我创建了一个程序,以便我可以测试我的后端 API 服务器/登录功能。我使用超级代理向服务器发送请求,一切正常,除了登录会话与我的实际浏览器登录会话无关。

当我 POST 到 /login 时,我会得到一个响应头,其中包含一个字段“Set-Cookie”,告诉我设置 cookie 值。当此 cookie 时,我可以使用后端服务器保持登录状态。但显然,尽管 POST /login 成功,superagent 并没有为我设置 cookie 值。

那么如何与浏览器共享会话/cookie 信息?

var request = require('superagent');

request.post('http://localhost:3000/login')
  .send({email: 'test@gmail.com', password: 'test@gmail.com'})
  .end(function(err, res){
    console.log(err)
    console.log(res.header)
  })

【问题讨论】:

    标签: node.js session cookies request superagent


    【解决方案1】:

    我假设您是从localhost:3000 以外的来源发出此请求,否则浏览器应该已经在发送该请求的 cookie。

    Superagent 在浏览器中使用XMLHttpRequest 对象来发出http 请求。默认情况下,cross-origin requests do not send cookies。为了让XMLHttpRequest 发送cookie/身份验证标头,您必须将请求的withCredentials 属性设置为true。超级代理makes this easy。只需根据您的请求使用.withCredentials() 方法:

    var request = require('superagent');
    
    request.post('http://localhost:3000/login')
      .send({email: 'test@gmail.com', password: 'test@gmail.com'})
      .withCredentials()
      .end(function(err, res){
        console.log(err)
        console.log(res.header)
      })
    

    【讨论】:

    • 我猜 withCredentials() 不兼容 es6 吧?