Search code examples
node.jsexpressserver-side

Why authorised header is not pass through redirect?


I try to pass header through redirect. For some reason i don't get any value in the response header in the redirect path. I try to pass header of token through one route to another route via Express package, and then send it to GET response as a result of the answer. On the client side i should get the token and save it.

i got the path "/users/login" that use JWT to generate token and then save it in the header. After that use redirect to "/flights/" and i try to get access to the header but the header "token" is not exist. In the login route the header is exist.

here is the code of "/users/login" route

const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const bcryptjs = require('bcryptjs')

const user={}

const vt =(req,res,next)=>{

    if(req.headers.token)
        jwt.verify(req.headers.token,"havhav",(err,decoded)=>{
            if(err) res.status(403).send(err)
            else{
                next()
            }
        })
    else{
            bcryptjs.compare(req.body.pass,user.pass,(err,result)=>{
                if(err) throw err
                if(result){
                    jwt.sign({
                        username:user.username
                    }, 'havhav', (err, token) => {
                        if (err) throw err
                        res.header('token', token) 
                        next()
                    })

                }
                else
                    res.status(403).send("unauthorized")
            })

    }

}
router.post('/login',vt,(req,res)=>{

    res.redirect(307,'/flights')
})
module.exports = router

here is the code of "/flights/" route

const express = require('express')
const router = express.Router()

router.post("/",(req,res)=>{

    res.send("welcome to flights")
})

module.exports = router

here is the client side

try{
    let data = await fetch('http://localhost:3000/users/login',
    {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: JSON.stringify({"username":"idan","pass":"123456"}) 
      }
    )
    console.log(data);
    }
    catch(err) {console.log(err);}

thanks!


Solution

  • Just paste this code in a separate file say vt.js and export it.

    const express = require('express')
    const router = express.Router()
    const jwt = require('jsonwebtoken')
    const bcryptjs = require('bcryptjs')
    
    const user={}
    
    const vt =(req,res,next)=>{
    
        if(req.headers.token)
            jwt.verify(req.headers.token,"havhav",(err,decoded)=>{
                if(err) res.status(403).send(err)
                else{
                    next()
                }
            })
        else{
                bcryptjs.compare(req.body.pass,user.pass,(err,result)=>{
                    if(err) throw err
                    if(result){
                        jwt.sign({
                            username:user.username
                        }, 'havhav', (err, token) => {
                            if (err) throw err
                            res.header('token', token) 
                            next()
                        })
    
                    }
                    else
                        res.status(403).send("unauthorized")
                })
    
        }
    
    }
    module.exports=vt;
    

    Then in login page:

    const express = require('express')
    const router = express.Router()
    const middlecheck=require('./vt.js');
    router.post('/login',middlecheck.vt,(req,res)=>{
    
        res.redirect(307,'/flights')
    })
    module.exports = router;
    

    Then in "/flights/" route

    const express = require('express')
    const router = express.Router()
    const middlecheck=require('./vt.js');
    router.post("/",middlecheck.vt(req,res)=>{
    
        res.send("welcome to flights")
    });
    module.exports = router;
    

    Then you can get it in the routes by using req.accesstoken