Not able to verify The user by token generated in raectjs`
I am new to reactJs. I want to make login system in reactjs. I am successfully logged in and navigate to my dashboard. I tried other solution but it wouldn't help me
But i want to go to my Blog page after the I login to my account, so I AM TRYING TO VERIFY THE USER, THAT HE/SHE IS LOGGED IN OR NOT BY TOKEN GENERATED AT THE TIME OF LOGIN
Problem
Problem is that login is successfully but whenever i am going to blog page it redirects to login page .i.e user is not verifying by token generated but token is showing in my local storage. token is successfully generated but it is not verified
Error i got
- Error i got in vs code terminal(backend response)
TypeError:开发者_C百科 Cannot read properties of undefined (reading 'jwtoken')
at Authenticate (C:\Users\kumar\Desktop\kms\server\middleware\authenticate.js:9:35)
Error i got in chrome console
Failed to load resource: the server responded with a status of 401 (Unauthorized)
Blog.jsx:31 SyntaxError: Unexpected token 'N', "No token provide" is not valid JSON
dash:1 Failed to load resource: the server responded with a status of 401 (Unauthorized)
Blog.jsx:31 SyntaxError: Unexpected token 'N', "No token provide" is not valid JSON
Error i got in chrome>network tab>response
No token provide
WHAT I TRIED
I tries to verify the user token generated by using middleware. in middle ware i verify the token and make the user login in
Authenticate.js(middleweare)
const jwt = require("jsonwebtoken")
const User = require("../models/SignupSchema")
const Authenticate = async (req, res, next) => {
try {
const token = req.cookies.jwtoken
const verifytoken = jwt.verify(token,process.env.SECRET_KEY)
const rootUser = await User.findOne({_id:verifytoken._id,"tokens.token":token})
if(!rootUser){
throw new Error("User not found")
}
req.token = token
req.rootUser = rootUser
req.userId = rootUser._id
console.log(rootUser);
next()
} catch (err) {
res.status(401).send("No token provide")
console.log(err);
}
}
module.exports = Authenticate
Auth.js(backend)
router.get("/dash",authenticate,(req,res)=>{
console.log("hello this about page");
res.send(req.rootUser)
})
Blog.jsx(reactjs)
import React,{useState,useEffect} from 'react'
import { useNavigate } from 'react-router-dom'
const Blog = () => {
const [userData,setuserData] = useState()
const navigate = useNavigate()
const callAboutPage = async ()=>{
try {
const res = await fetch("/dash",{
method :"GET",
headers : {
Accept : "application/json",
"Content-Type" : "application/json"
},
credentials : "include"
})
const data = await res.json()
console.log(data);
setuserData(data)
if(!res.status === 200){
const error = new Error(res.error)
throw error
}
} catch (error) {
console.log(error);
navigate("/login")
}
}
useEffect(()=>{
callAboutPage()
},[])
return (
<>
I tried to use middleware and i am expecting to user should be verified
精彩评论