Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookies not saved when using npm request library

I have a local environment and I'm trying to login to a service. I'm using the 'request' library in the client and Express and express-session in the service.

I'm using Chrome and when I login to the service I get the following response headers:

FROM: http://app.dev:3000
TO: http://app.dev:4000/login/local

HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://app.dev:3000
Vary: Origin, X-HTTP-Method-Override
Access-Control-Allow-Credentials: true
Content-Type: application/json; charset=utf-8
Content-Length: 304
ETag: W/"130-fdQBs605dSVTeEqXEuXrvdcQTLk"
set-cookie: auth=TOKEN; Path=/; Expires=Sun, 25 Jun 2017 01:48:41 GMT
Date: Sat, 24 Jun 2017 13:48:41 GMT
Connection: keep-alive

When I login with Postman the cookie gets stored correctly. Subsequent requests through Postman include the cookie and everything is working fine.

But doing the same request with the npm request library it won't save the cookie and subsequent requests to the backend do not include cookies. Example request to the service after logging in. No cookie sent.

like image 573
Janne Annala Avatar asked Jun 24 '17 15:06

Janne Annala


People also ask

How to check cookies in Node js?

We can check the cookies by visiting localhost:3000/getcookie.

How cookies work in Nodejs?

Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps us keep track of the user's actions. Now to use cookies with Express, we will require the cookie-parser.


1 Answers

The request library documentation doesn't mention the withCredentials option but setting it to true fixes the issue. The cookie now gets saved and is being sent on subsequent requests.

const requestBase = request.defaults({
  baseUrl: 'http://app.dev:4000/',
  withCredentials: true,
});
like image 165
Janne Annala Avatar answered Oct 03 '22 08:10

Janne Annala