Home > Software engineering >  React JS not accepting cookies from express sever
React JS not accepting cookies from express sever

Time:02-04

I'm sending cookies from express server (res.cookie()) but this ain't working with my front end even though I include {withCredentials:true} in the get requests but it just doesn't work in the browser, no cookies are set in the application tab in browser. BUT if I try the requests with postman the middleware works perfectly and cookies are shown. I tried different browsers and different devices, but none. cors config:

app.use(
  cors({
  
    credentials: true,
    origin: [
      "http://localhost:3000", 
    ],
    methods: ["GET", "POST"],

  })
);

cookie parser config:

app.use(cookieParser())

this is the get request to check if the user is already logged in :

    await axios
        .get("http://192.168.0.141:3001/login", { withCredentials: true })
        .then(async (response) => {

            if (response) {
                loggedIn = true
            }
        })
        .catch(async err => {

            loggedIn = false
        })

the middleware of jwt :

const validateToken = (req, res, next) => {
    const accessToken = req.cookies["access-token"]
    if (!accessToken) { return res.status(400).json({ error: "user not authenticated" }) }
    try {
        const validToken = jwt.verify(accessToken, "test");
        if (validToken) {
            req.authenticated = true
            return next();
        }
    } catch (error) {
        return res.status(400).json({ error: error });
    }
}

If you need more clarification please tell me , thank you for helping

CodePudding user response:

You did not mention if you used cookie-parser; to use cookies in express you need to install cookie-parser and use it as follows:

npm install cookie-parser;

Then in your app;

const cookieParser = require('cookie-parser');

// when adding middlewares

app.use(cookieParser())

CodePudding user response:

Are you sure that no cookies are set? How are you checking that? Does the response contain the Set-Cookie header? What cookie parameters are you using (secure, same-site?). Remember that cookies in a browser are saved under the domain which set the cookie. If you're checking in the Application tab of developer tools, then you have to open the developer tools on http://192.168.0.141:3001 not on http://localhost:3000. In your SPA's Application tab you won't see those cookies, but the browser should send them with any XHR request, so you should see them in the request's Cookie header in the Network tab.

  •  Tags:  
  • Related