【问题标题】:How do you handle cookies with request-promise?你如何处理带有 request-promise 的 cookie?
【发布时间】:2017-06-23 06:02:44
【问题描述】:

我在抓取需要身份验证且正在使用会话 cookie 的网站时遇到问题。会话需要一个带有 POST 的请求,然后身份验证会批准。但是当我想获取需要身份验证的网页时,它会返回“未授权”。我想我需要一种方法来使用 GET 请求带来会话 cookie,但我不知道如何!我的依赖是 request-promise(https://www.npmjs.com/package/request-promise)。

代码如下:

var rp = require("request-promise");

    var options = {
    method: "POST",
    uri: "http://website.com/login",
    form: {
        username: "user",
        password: "pass",
    },
    headers: {},
    simple: false
};

rp(options).then(function(response) {
    console.log(response); // --> "Redirecting to login/AuthPage"
    request("http://website.com/login/AuthPage", function(err, res, body) {
        console.log(body); // --> "Unauthorized"
    })
}).catch(function(e) {
    console.log(e)
})

我猜您必须将请求放入“Jar”(https://github.com/request/request#requestjar) 中才能访问下一个请求 URL,但我如何设置请求承诺以创建 cookie-jar ?

【问题讨论】:

    标签: javascript angularjs session cookies


    【解决方案1】:

    您的问题是如何在身份验证后保持会话。 这意味着,在使用用户名和密码登录后,服务器将返回一个带有标识符的 cookie。然后,您需要将该 cookie 附加到您的所有功能请求中。
    request-promise 很简单。只需通过启用jar 选项来保持跟踪会话,然后对所有请求使用相同的request 对象。 一起来看看

    var request = require("request-promise").defaults({ jar: true });
    var options = {
        method: "POST",
        uri: "http://website.com/login",
        form: {
            username: "user",
            password: "pass",
        },
        headers: {},
        simple: false
    };
    
    request(options).then(function(response) {
        request("http://website.com/login/AuthPage", function(err, res, body) {
            console.log(body);
        })
    }).catch(function(e) {
        console.log(e)
    })
    

    【讨论】:

      【解决方案2】:

      在进行休息调用时使用以下对象。

      var request = require("request-promise").defaults({jar: true});
      

      添加您自己的 cookie

      var tough = require('tough-cookie');
      
      // Easy creation of the cookie - see tough-cookie docs for details
      let cookie = new tough.Cookie({
          key: "some_key",
          value: "some_value",
          domain: 'api.mydomain.com',
          httpOnly: true,
          maxAge: 31536000
      });
      
      // Put cookie in an jar which can be used across multiple requests
      var cookiejar = rp.jar();
      cookiejar.setCookie(cookie, 'https://api.mydomain.com');
      // ...all requests to https://api.mydomain.com will include the cookie
      
      var options = {
          uri: 'https://api.mydomain.com/...',
          jar: cookiejar // Tells rp to include cookies in jar that match uri
      };
      

      然后拨打电话。关于 request-promise 的更多详情: https://www.npmjs.com/package/request-promise

      【讨论】:

        猜你喜欢
        • 2011-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-24
        • 1970-01-01
        • 2016-10-29
        相关资源
        最近更新 更多