繁体   English   中英

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

[英]How do you handle cookies with request-promise?

我在抓取需要身份验证的网站时遇到问题,并且正在使用会话 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)
})

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM