如何在NodeJS中维护请求会话

如何在NodeJS中维护请求会话

本文介绍了如何在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.

第一个现在的问题是登录。我试过用请求 POST 登录信息,但响应我get似乎没有登录。

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.

作为后续工作,我最终使用获取我需要的功能

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中维护请求会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 04:46