Home > Blockchain >  How can i get my data from headers in nodejs?
How can i get my data from headers in nodejs?

Time:04-28

I'm learning nodejs. Actually I'm trying to write AUTH with Jwt token. I can generate token and save it in headers.

     router.post('/login', async(req, res) => {
      const {username, password } = req.body;
      const user = await Users.findOne({ where: {name: username}})
      if (!user) res.json({error: "Users doesnt exist"});
      
      bcrypt.compare(password, user.password).then((match) => {
        if (!match) res.json({error: "Wrong username and password combination"})
        const accessToken = sign({name: user.username, id: user.id}, "tajneheslo", {expiresIn: "2h"}); 
        res.setHeader('accessToken', accessToken);
        
    });
      
});

but after that i'm stuck. I dont know how can i get data from headers. In middleware for example. I'm beginner so please don't judge me.

CodePudding user response:

You can get headers by using req.headers which will give all the headers as an object. Then you can get the value accessToken by req.headers.accessToken.

CodePudding user response:

You can access to token with : req.headers.authorization and example of writing a middleWare not the best not the cleanest is code below :

const authenticateMiddleWare = async (req, res, next)=> {
  try {
    const authorization = (req.headers.authorization ||
      req.headers.Authorization) as string
    if (!authorization) {
      throw new Error('there is no bearer token in the headers')
    }

    const accessToken = authorization.split(' ')[1]
    const jwt = verify(
      jwtToken,
      'YOUR_JWT_SECRET'
    )
    //find your user by the data that exist in jwt for example userId
    // just as asn example define a function to fetch your user from database
    const user = await findUserbyUserId(jwt.id)
    if(!user) throw new Error('Ooops user not found')
    //put the data you need in res.locals or re.user or any other convention as an       example : 
    res.user = {
      userId: user.id,
      name: user.name,
      nationalCode: user.nationalCode,
      //or any othe data you need in your controller
    }
    //then you can have access to this data any where you have access to res
    //use this middelware on any route you want
    next() //pass it 
  } catch (error) {
    //log or console your error for better tracibility
    console.log('error in authenticate middleWare : ', error)
    res.status(401).send('UNAUTHORIZED')
  }
}

in the next step you can use redis for advance scenarios

  • Related