Connecting to a PHP website with Node.js and keep session

随声附和 提交于 2019-12-03 00:49:08

If you set jar: true in your options or use your own custom cookie jar, then request will remember cookies set by the server so that you can keep your session between requests.

mscdex thanks for your answer! But unfortunately it did not work for me :/

hyubs thanks to you too.

Finally I carried on to use Mocha + Request.

Basically what I did is:

  1. Connect through a POST request to the login page and get the PHPSESSID cookie that is returned in the response header.

  2. Pass the cookie in the header in the next requests that target a URL where you have to be logged.

Here is my code :

var params = {
    email: 'your_username',
    password: 'your_password'
};
var paramsString = JSON.stringify(params);

// Login to the application
request.post('http://localhost/biings/front-end/rest/auth',
{ 
    headers: {
        "Content-Type" : "application/json",
        'Content-Length' : paramsString.length
    },
    body: paramsString,
},function (error, response, body) {
    // get the PHPSESSID (the last one) that is returned in the header. Sometimes more than one is returned
    var sessionCookie = response.headers['set-cookie'][response.headers['set-cookie'].length - 1];
    sessionCookie = sessionCookie.split(';');
    sessionCookie = sessionCookie[0];
    // Write it in a file (this is a quick trick to access it globally)
    // e.g.: PHPSESSID=ao9a1j0timv9nmuj2ntt363d92 (write it simply as a string)
    fs.writeFile('sessionCookie.txt', sessionCookie, function (err) 
    {
        if(err)
        {
            return console.log(err);
        } 
    });
});

// don't care about this it() function (it's for Mocha)
it("test 1", function(done)
{
    // Get the cookie
    fs.readFile('sessionCookie.txt','utf8', function (err, data) 
    {
        if(err)
        {
             throw err; 
        }
        else
        {
         // Launch a request that includes the cookie in the header
         request.get('http://localhost/biings/front-end/rest/group', 
         {
              headers: {"Cookie" : data},
         }, function (error, response, body) {
             // Check your request reaches the right page
                 expect(response.statusCode).equals(200);
             console.log(body);
                 done();
         });
        }
    }); 
});

It works like a charm for me.

Tell me if you see something wrong or which could be optimized :)

Michaël

Instead of using the request module, use headless browsers like PhantomJS and zombie.js. You can even emulate user interaction with these.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!