Super-agent shared session / cookie info with actual browser
I am creating a program so that I can test my server side APIs / login. I send requests to the server using a super agent and everything works fine, except that the login session has nothing to do with my actual browser login session.
When I POST to / login, I will receive a response header with a "Set-Cookie" field that will tell me the cookie value. When this cookie I can stay online with the backend server. But from the looks of it, the super agent didn't set the cookie for me, although the POST / login succeeded.
So how do I share session / cookie information with the browser?
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)
})
source to share
I am assuming that you are making this request from a source other than localhost:3000
, otherwise the browser must already be sending cookies for the request.
The super agent uses the object XMLHttpRequest
in the browser to make http requests. By default, cross-origin requests do not send cookies . To get XMLHttpRequest
to send authentication cookies / headers you must set the withCredentials
request property to true
. Super Agent makes this easy . Just use the method .withCredentials()
as per your request:
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)
})
source to share