超级代理与实际浏览器共享会话/ cookie信息



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

当我POST到/登录,我将得到一个响应头与一个字段' set - cookie ',告诉我设置cookie值。当这个cookie,我可以保持登录与后端服务器。但显然超级代理没有为我设置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)
  })

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

Superagent使用浏览器中的XMLHttpRequest对象来发出http请求。缺省情况下,跨域请求不发送cookie。为了让XMLHttpRequest发送cookie/认证头,您必须将请求的withCredentials属性设置为true。超级特工让这一切变得简单。只需在您的请求上使用.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)
  })

最新更新