带有request.jar的node.js cookie

时间:2015-11-03 18:23:46

标签: node.js authentication cookies jar request

我正在抓取一个需要身份验证的网站。我正在使用node.js并请求使用jar来存储cookie。

我的问题: 我有两条路线/登录和/ api,当我登录网站时,我将cookie存储在登录路径/文件中,如何在/ api中使用相同的cookie?

        login.js:

        var request = require('request');
        var jar = request.jar();

        var payload = querystring.stringify({
            username: username,
            password: password,
            request_token: token,
        });

        var options = {
            ..
            ..
            method: 'POST',
            body: payload,
            jar: jar <---------- Valid cookie
        };

       request(options, function (error, response, body) {
            // Code here
        });


       --------------------------------

        api.js:

        var request = require('request');
        var jar = request.jar();

           var options = {
            method: "get",
            url: baseUrl,
            jar: jar <-------- Not sat anymore
        };


        request(options, function (error, response, body) {

            if (error) {
                res.send(error);
                return;
            }

1 个答案:

答案 0 :(得分:3)

您可以创建一个新模块并集中该方法。在这里,我创建了模块jar.js,它具有允许设置/获取jar的导出函数。

您的原始代码现在只需要这种新方法。在每个文件中,我添加了行var jar = require('./jar');

jar.js:

var request = require('request');
var jar;

module.exports = function getJar() {
   if(jar)
     return jar;
   else {
     jar = request.jar();
     return jar;
  }
}

module.exports = function setJar(jarParam) {
  jar = jarParam;
}

 --------------------------------
  login.js:

    var jar = require('./jar');
    var request = require('request');
    jar.setJar(request.jar());

    var payload = querystring.stringify({
        username: username,
        password: password,
        request_token: token,
    });

    var options = {
        ..
        ..
        method: 'POST',
        body: payload,
        jar: jar.getJar() <---------- Valid cookie, from jar module
    };

   request(options, function (error, response, body) {
        // Code here
    });


  --------------------------------

    api.js:

    var request = require('request');
    var jar = require('./jar');

       var options = {
        method: "get",
        url: baseUrl,
        jar: jar.getJar() <---------- Valid cookie, from jar module
    };