如何在 NodeJS 中维护请求会话 [英] How to maintain a request session in NodeJS

查看:26
本文介绍了如何在 NodeJS 中维护请求会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 NodeJS 来抓取需要通过 POST 登录的网站.然后,一旦我登录,我就可以通过 GET 访问一个单独的网页.

I'm trying to use NodeJS to scrape a website that requires a login by POST. Then once I'm logged in I can access a separate webpage by GET.

现在的第一个问题是登录.我尝试使用 requestPOST 登录信息,但我得到的响应似乎没有被记录

The first problem right now is logging in. I've tried to use request to POST the login information, but the response I get does not appear to be logged in.

exports.getstats = function (req, res) {
    request.post({url : requesturl, form: lform}, function(err, response, body) {
        res.writeHeader(200, {"Content-Type": "text/html"});
        res.write(body);
        res.end();
    });
};

这里我只是转发我返回的页面,但我返回的页面仍然显示登录表单,如果我尝试访问另一个页面,它会说我没有登录.

Here I'm just forwarding the page I get back, but the page I get back still shows the login form, and if I try to access another page it says I'm not logged in.

我认为我需要维护客户端会话和 cookie 数据,但我找不到任何资源来帮助我理解如何做到这一点.

I think I need to maintain the client side session and cookie data, but I can find no resources to help me understand how to do that.

作为后续,我最终使用 zombiejs 来获得我需要的功能

As a followup I ended up using zombiejs to get the functionality I needed

推荐答案

您需要制作一个 cookie jar 并为所有相关请求使用同一个 jar.

You need to make a cookie jar and use the same jar for all related requests.

 var cookieJar = request.jar();
 request.post({url : requesturl, jar: cookieJar, form: lform}, ...

理论上,这应该允许您以登录用户的身份使用 GET 抓取页面,但前提是您使实际的登录代码正常工作.根据您对登录 POST 响应的描述,这可能实际上尚未正常工作,因此在您首先解决登录代码中的问题之前,cookie jar 将无济于事.

That should in theory allow you to scrape pages with GET as a logged-in user, but only once you get the actual login code working. Based on your description of the response to your login POST, that may not be actually working correctly yet, so the cookie jar won't help until you fix the problems in your login code first.

这篇关于如何在 NodeJS 中维护请求会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆