我在抓取一个需要身份验证的网站时遇到了问题,并且正在使用会话cookie。会话需要一个带有POST的请求,然后身份验证就会批准。但是当我想要获取需要认证的网页时,它会返回“未授权”。我想我需要一种方法来将会话cookie与GET-request一起带来,但我不知道如何实现!我的依赖是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的请求承诺呢?
发布于 2017-09-19 20:05:43
您的问题是如何在身份验证后保持会话。这意味着,在使用用户名和密码登录后,服务器将返回一个带有标识符的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)
})发布于 2018-09-03 14:10:31
在进行rest调用时使用以下对象。
var request = require("request-promise").defaults({jar: true});添加您自己的cookies
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的更多详细信息
https://stackoverflow.com/questions/42065364
复制相似问题