I'm using request.

I want to login a website only once, then use the same connection until it expires, so I won't have to login every time I send a request.

How can I do that?

I have tried the code below, but it doesn't retain the session. I'm using Redis to save cookie values, this is probably the wrong way, though. Two cookies are generated after you log in.

var request = require("request").defaults({jar: true, followAllRedirects: true}); var options1 = { method: 'GET', url: 'homepageURL', headers: { 'cache-control': 'no-cache', 'accept-language': 'tr,en-US;q=0.9,en;q=0.8,ru;q=0.7,it;q=0.6,fr;q=0.5,de;q=0.4,es;q=0.3,sv;q=0.2,nl;q=0.1,pl;q=0.1,pt;q=0.1,nb;q=0.1', 'accept-encoding': 'gzip, deflate, br', referer: 'URL', accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36', 'upgrade-insecure-requests': '1' } }; request(options1, function (homeError, homeResponse, homeBody) { if (homeResponse.statusCode == 200) { var form = {"username": "myusername", "password": "mypassword", "secret": "mysecret", "action": "login"}; var options2 = { method: 'POST', url: 'siteurl + "/" + login.asp', headers: { 'cache-control': 'no-cache', 'accept-language': 'tr,en-US;q=0.9,en;q=0.8,ru;q=0.7,it;q=0.6,fr;q=0.5,de;q=0.4,es;q=0.3,sv;q=0.2,nl;q=0.1,pl;q=0.1,pt;q=0.1,nb;q=0.1', 'accept-encoding': 'gzip, deflate, br', referer: 'URL', accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36', 'content-type': 'application/x-www-form-urlencoded', 'upgrade-insecure-requests': '1', origin: url + "/" + login.asp }, form: form }; request(options2, function (loginError, loginResponse, loginBody) { if (loginResponse.statusCode == 200) { console.log("Successfully logged in."); client.set("cookie1", homeResponse.request.headers.cookie, function () { client.set("cookie2", loginResponse.request.headers.cookie, function () { nrp.emit('profile', {}); }); }); } }); } });

Profile test