你如何处理带有请求承诺的 cookie?

Jes*_*per 5 javascript cookies session angularjs

我在抓取需要身份验证的网站时遇到问题,并且正在使用会话 cookie。会话需要一个带有 POST 的请求,然后认证通过。但是当我想获取需要身份验证的网页时,它返回“未授权”。我想我需要一种方法来将会话 cookie 与 GET 请求一起带入,但我不知道如何!我的依赖项是 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)
})
Run Code Online (Sandbox Code Playgroud)

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

use*_*693 7

您的问题是如何在身份验证后保持会话。这意味着,使用用户名和密码登录后,服务器将返回一个带有标识符的 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)
})
Run Code Online (Sandbox Code Playgroud)