如何使用NodeJs请求GET模块发送cookie? [英] How can I send cookie using NodeJs request GET module?

查看:483
本文介绍了如何使用NodeJs请求GET模块发送cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发NodeJs中的一个项目,该项目要求我登录以获取cookie,该cookie将在检索数据时使用。我有以下代码可以成功登录并以正确的格式返回Cookie:

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

            }
            )

});

我的问题是,当我尝试执行GET请求并附加cookie时,该用户说未经授权,这意味着未正确传递Cookie,有人会知道如何使用请求模块执行此操作吗?谢谢

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

推荐答案

几个小时后,我找到了一个解决方案,而不是:

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
          }

它必须是:

 //requesting data
        request({
          url: 'http://localhost/delivery-stats',
          method: "GET",
          header: {
            'Cookie': 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.

这篇关于如何使用NodeJs请求GET模块发送cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆