Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  188] [ 3]  / answers: 1 / hits: 29565  / 9 Years ago, mon, october 26, 2015, 12:00:00

I'm working on a project in NodeJs that requires me to login to get a cookie which would be used when retrieving data. I've got following code which succeeds to log in and return me a cookie with correct formatting:



 var request = require('request');

var requestData = {
username:myUsername,
password:myPassword
}

//request post request
request({
url: 'http://localhost/login',
method: POST,
json: requestData}
,function(err, res) {
if(err){
console.log(it did not work: + err)
}

console.log(res.statusCode)//logs as 201 sucess
console.log(heres the cookie: +res.headers['set-cookie']) //returns cookie in correct format
var cookie = res.headers['set-cookie']
//requesting data
request({
url: 'http://localhost/delivery-stats',
method: GET,
header: {
'set-cookie': cookie
}
},function(err,response){
console.log(response.headers) // one of the headers says user is not authorised

}
)

});


My problem is that when i try to do GET request with cookie attached to it it says that user is unauthorised, which means that the cookie was not passed correctly, anyone would know on how to do this using request module? Thanks


More From » node.js

 Answers
7

After a few hours I've found a solution, instead of :



 //requesting data
request({
url: 'http://localhost/delivery-stats',
method: GET,
header: {
'set-cookie': cookie
}


it had to be :



 //requesting data
request({
url: 'http://localhost/delivery-stats',
method: GET,
header: {
'Cookie': cookie
}


Because that is correct way to send cookies via request, but it was poorly documented so it took me some time to figure out. Hopefully this would help someone in the future.


[#64599] Friday, October 23, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
krystadesiraeo

Total Points: 493
Total Questions: 93
Total Answers: 100

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
;