Search code examples
reactjsnode.jscookiesbackendweb-developer-toolbar

regarding the retreival of the user token


Unable to retrieve token from the headers, JWT token is not storing in cookie storage as I am unable to retrieve user info from local storage. I am retrieving the user information from the jwt token, when I have encountered an unique error, When I have written code it is giving output as undefined also the cookie that was stored under the header seems to be incorrect. I am doing this because I want to retrieve the user email from the token. Besides this the data is not storing in cookie storage, if you asking question of why I am using cookie storage, it is because I am not getting solution of how can we get token from local storage . The funniest part is, when I have runned it in thunder client is generated the correct result but the output is undefined when token was called from browser.The codes and the token are mentioned below

Code to store cookie in the cookie storage but it is not storing in cookie storage

router.post('/signin',async(req,res)=>{
// some more validation need to be done
// like if the user exist and if so is the password correct
// creating signup logic

console.log("reached signin page successfully");

const email = req.body.email;
const password = req.body.password;
const users = await User.findOne({
    email
})


if(users)
{
    console.log("successfully logged in")
    const passcompare = password === users.password;
    if(passcompare)
    {  
        const token = jwt.sign
        (
            email
        ,JWT)

        // res.json
        // ({
        //     success:true,
        //     msg:token
        // })
        
        res.status(200);
        res.cookie("cookie",token,
        {httpOnly:true
        // secure:process.env.NOD_ENV==="production",
        // maxAge:1000,
        // signed:true,
        }
    )

        res.json({
            success:true,
            token
        });
    }   
    else
    {
        res.json
        ({
            success:false,
            msg: "password incorrect"
        })
    }
 }
 else
 {
    res.json({
        success:false,
        msg:"No user found With the above credentials"
    })
 }

})

// Now using middlewere here 

router.get('/signinn',fetchuser,async (req,res)=>
{
// const autheader = req.headers.token;
// console.log("Token value is ", autheader);
console.log("reached signnn");
let userdata = await User.findOne({
 email:req.email
})

if(userdata)
{
    res.json({
        userdata
    })
 }
})

// middleware 

const fetchuser = async (req,res,next)=>
{
console.log("reached middleware")
const token2 = req.headers.token;
// const token2 = req.cookies.cookie; 
// console.log(token2)
if(!token2)
{
    res.status(401)
    .send
    ({
        msg:"No token found"
    })
}
else
{
    try
    {
        const data = jwt.verify(token2,JWT);
        req.email = data;   
        next();
    }
    catch(error)
    {
        res.status(401)
        .send
        ({
            msg:"No token found"
        })
    }
  }
}

// frontend code where the data is being fetched

const [username,setusername] = useState()

useEffect(()=>{
fetch('http://localhost:4000/user/signinn')
.then((response)=>response.json())
.then((data)=>setusername(data))

},[])
console.log("hello",username);

This is the output from the header section Don't know what is this

cookie=eyJh%---some more text ------% dRNc3d4Y7o; Path=/; HttpOnly`

Solution

  • Yes, I finally found the answer. And the answer is that, we can get the token using the following code and then stored the token to the file. The middle ware will read the token from the file validate the token with "secret Key" and give us the output as email. The following is the code I have used to get token from the browsers.

    Include this code at the require section.

    var LocalStorage = require('node-localstorage').LocalStorage;
    localStorage = new LocalStorage('./scratch');
    

    It will create the folder named scratch

    localStorage.setItem("token1",token);
    

    This will create a file named token1 inside scratch folder with the value of token. this section must be put under the section where the token is generated so that it can capture the token value and pass to the file token1 for storage.

    const token2 = localStorage.getItem('token1')
    

    This will get the token1(that was previously stored on the token1 file) value and stored in token2

    Now you have token, verify it and just get the details of the user.

    If there exist any other solution please do provide me.

    Hope this will help !!