Skip to content
Advertisement

React Node Unable to pass cookie to the browser (crocs error)

For some reason I am unable to store cookie in my browser.

This is the first time I am working with React And NodeJS

My React application is working on localhost:3000 and NodeJS application on localhost:8080

The Git repository for the same happens to be this

So, I am successfully able to login, store the credentials in DB and probably serialise and de-serialise.

I am not sharing the code for Google Strategy and serialise and de-serialise since I believe that problem doesn’t presist here (In case you think that you would need to view it click here

This Google redirect returns at following callback

JavaScript

In my server.js (main file, I start node server by doing node server.js), I am doing this to store cookie

JavaScript

And then when I do this in my react frontend

JavaScript

Where my localhost:3000/ looks like this

JavaScript

It always log res.json("user does not exsist") but if I directly go to localhost:3000 in my browser, I can see my req.user < [See: update below question]

Ps; I am enabling cross-origin request in my browser

[Question:] Can someone please help me in finding out what I could be doing wrong?

[Update:] It appears we might be having crocs error, I have changed my code and I am getting this as an error in frontend

Access to XMLHttpRequest at ‘localhost:8080’ from origin ‘localhost:3000’ has been blocked by CORS policy: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute

If I remove {withCredentials: true} in my axios request the above error disappears but then it logs user does not exsist in response.data

Advertisement

Answer

So send Cookies via REST its neccecary to:

Set Cors serverside:

JavaScript

For Frontend you need to setup a call like this:

JavaScript

you can also use fetch asynchronous:

JavaScript

this, of course, applies to using a rest service with json bodies. If you rely on another structure than json, you need to parse your response manually.

Also, An interested article on web about cors https://50linesofco.de/post/2017-03-06-cors-a-guided-tour

Advertisement