How can I send cookie using NodeJs request GET module?

你。 提交于 2020-12-30 06:59:05

问题


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


回答1:


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.




回答2:


For anyone stumbling across this in 2019+, the correct way to add a cookie to a request is using the cookie jar property setCookie. request's cookie jar is based on tough-cookie, and you can reference that package's documentation for more detail.

// Require the request     
const request = require('request');

// Setup the cookie jar to carry cookies
const cj = request.jar();

// Add your cookie to the jar (URL is parsed into cookie parts)
cj.setCookie(stateCookie, 'https://yoursite.com/');

// Send your request and include the cookie jar
request(
    'https://request-site.com/api/things', 
    { jar: cj },
    (error, response, body)=>{
        // do things
    }
);


来源:https://stackoverflow.com/questions/33347685/how-can-i-send-cookie-using-nodejs-request-get-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!