I am using the request
package to create my server side requests. I wrote authentication middleware that checks for a cookie/session id for all requests. Therefore, is there a way I include the user's cookie as part of the request? Here is my current code:
var cookie = parseCookie.parseCookie(req.headers.cookie);
request('http://localhost:3000/users/api', function(error, response, body) {
console.log(body); //this console.logs my login page since requests w/o valid cookies get redirected to login
res.render('../views/admin');
});
Currently, this returns 'no cookie found' in the console. However, if I turn off my authentication middleware, the code above works as intended.
Additional info:
The cookie I want is the end user's cookie located on the browser. The end user's cookie is created by the app whenever the user logs in.
Update - solution attempt 1:
I tried this from the documentation:
var cookie = parseCookie.parseCookie(req.headers.cookie);
var cookieText = 'sid='+cookie;
var j = request.jar();
var cookie = request.cookie(cookieText);
var url = 'http://localhost:3000/users/api';
j.setCookie(cookie, url);
request({url: url, jar: j}, function(error, response, body) {
request('http://localhost:3000/users/api');
});
However, the console is still returning 'no cookie found'
Can someone help?
Thanks in advance!
Let me explain about cookies and that will probably show you why it's hard to get the cookie you want.
http://localhost:3000
, that server creates a login cookie and returns it as part of the login response.http://localhost:3000
domain and port.http://localhost:3000
, the browser sends all cookies it has previously saved for that particular domain and port with the request to the server.Now, on to your node.js code. You show a block of node.js code that is trying to access the same http://localhost:3000
server. But, the cookies are stored in the user's browser. Your node.js code cannot get them from the browser as the browser guards them and will only reveal them when the browser itself sends a request to http://localhost:3000
.
If you do actually have the right cookie in your node.js code, then you can set it on your request like this:
request({url: 'http://localhost:3000/users/api', headers: {Cookie: somedataHere}}, function(error, response, body) {
console.log(body); //this console.logs my login page since requests w/o valid cookies get redirected to login
res.render('../views/admin');
});
Relevant documentation for custom headers in the request
module is here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With