我在抓取需要身份验证且使用 session cookie 的网站时遇到问题。 session 需要使用 POST 的请求,然后身份验证会批准。但是当我想获取需要身份验证的网页时,它返回“未经授权”。我想我需要一种方法来将 session cookie 与 GET 请求一起使用,但我不知道该怎么做!我的依赖项是请求 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,但是我如何设置请求 promise 来创建一个 cookie-jar ?
最佳答案
您的问题是如何在身份验证后保持 session 。
这意味着,在使用用户名和密码登录后,服务器将返回一个带有标识符的 cookie。然后,您需要将该 cookie 附加到所有功能请求中。
request-promise
很简单。只需通过启用 jar
选项来保持跟踪 session ,然后对所有请求使用相同的 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)
})
关于javascript - 您如何处理带有请求 promise 的 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42065364/