Home > Enterprise >  React - How to send a cookie along fetch and get it in the backend NodeJS?
React - How to send a cookie along fetch and get it in the backend NodeJS?

Time:01-12

I have a project where I set a cookie with universal-cookie.

cookies.set('auth-token', data);

I then have a fetch request:

  const getMeals = async (date: Date) => {
    let res= await fetch("http://127.0.0.1:5000/meals/", {
      method: "POST",
      credentials: "same-origin",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        date: date
      }),
    });

    const data = await res.json();

    console.log(data);
  }

And a backend where it gets checked (NodeJs, ExpressJs):

module.exports = function(req, res, next){
    const token = req.header('auth-token');
    if(!token){
        return res.status(401).json('Access denied!');
    }
}

I see the cookie in my mozilla:

enter image description here

But I always get "Access denied!" -> that means the auth-token is not there... I hardcoded the auth-token into the fetch and it worked.

I checked several websites and almost all stackoverflow posts on this theme. I also checked the fetch-api documentation, but I couldnt come up with a solution...

Both the client and the server are running on localhost.

I hope someone can help me with this topic.

UPDATE

Andreas suggested that I should either set the header(frontend) or look for cookie- instead of header-values(backend).

I decided to do the second approach.

Server.js

var cookieParser = require('cookie-parser')
const usersRouter = require('./routes/users'); //where auth.js gets imported

app.use(cors());
app.use(express.json());
app.use(cookieParser());

app.use('/users', usersRouter);

I tried changing the position of app.use(cookieParser()); to above all others - didnt help.

auth.js

module.exports = function(req, res, next){
    const cookie = req.cookies['auth-token'];
    console.log(cookie);
}

The problem I now have is that the cookie value is undefined even though the cookie gets displayed in FireFox.

I tried to do the steps of this post, but this doesnt work afterwards I went to their official documentation and found nothing. I also stumbled upon this one, which makes me think that something is wrong in the frontend...

Frontend-File where I set the cookie:

import Cookies from 'universal-cookie';

const cookies = new Cookies();

const login = async () => {
        let res= await fetch("http://127.0.0.1:5000/users/login", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            email: (e.target as HTMLFormElement).email.value,
            password: (e.target as HTMLFormElement).password.value,
          }),
        });
    
        const data = await res.json()
        
        if(res.status === 200){
          cookies.set('auth-token', data);
          setUserId((jwt_decode(data) as any)._id);
          navigate("/");
        }else{
          alert(data);
        }
}

Does someone have an idea?

CodePudding user response:

I could fix the problem with the help of a friend. I had to add "proxy": "http://localhost:5000/" to my package.json in my React-Project, because the port is important for the cookie so localhost:5000 and localhost:3000 are not the same for it. I could also remove the app.use(cors()) from my NodeJs-Project, because of it.

CodePudding user response:

I would suggest you run your front end on http://127.0.0.1:3000

  • Related