Superagent与实际浏览器共享会话/ cookie信息

时间:2015-06-07 16:08:20

标签: node.js session cookies request superagent

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

当我发布到/ login时,我会得到一个带有“Set-Cookie”字段的响应标题,告诉我设置cookie值。当这个cookie我可以使用后端服务器保持登录状态。但显然superagent没有为我设置cookie值,虽然POST /登录成功。

那么如何与浏览器共享会话/ 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)
  })

1 个答案:

答案 0 :(得分:3)

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

Superagent使用浏览器中的XMLHttpRequest对象发出http请求。默认情况下,cross-origin requests do not send cookies。要使XMLHttpRequest发送Cookie /身份验证标头,您必须将请求的withCredentials属性设置为true。 Superagent 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)
  })