Superagent share session / cookie info with actual browser

4.9k views Asked by At

I create a program so that i can test my backend API server /login functionality. I send requests to the server using superagent and everything works fine except the login session has nothing to do with my actual browser login session.

When I POST to /login I will get a response header with a field 'Set-Cookie' that tells me to set cookie value. When this cookie I can stay loggedin with the backend server. But apparently superagent didn't set the cookie value for me although POST /login is successful.

So how do I share the session/cookie info with browser?

var request = require('superagent');

request.post('http://localhost:3000/login')
  .send({email: '[email protected]', password: '[email protected]'})
  .end(function(err, res){
    console.log(err)
    console.log(res.header)
  })
1

There are 1 answers

1
mlrawlings On

I'm assuming that you're making this request from an origin other than localhost:3000, otherwise the browser should already be sending the cookies for the request.

Superagent uses the XMLHttpRequest object in the browser to make http requests. By default, cross-origin requests do not send cookies. In order to get XMLHttpRequest to send cookies/authentication headers, you must set the withCredentials property of the request to true. Superagent makes this easy. Just use the .withCredentials() method on your request:

var request = require('superagent');

request.post('http://localhost:3000/login')
  .send({email: '[email protected]', password: '[email protected]'})
  .withCredentials()
  .end(function(err, res){
    console.log(err)
    console.log(res.header)
  })