there issuse in my code it does fetch from database which found an authorized but it is authorized data error is JsonWebTokenError: jwt malformed
here the requireAuth component
const jwt = require('jsonwebtoken');
const User = require('../Model/userModel');
const requireAuth = async (req, res, next) => {
const { authorization } = req.headers;
if (!authorization) {
return res.status(401).json({ error: 'Authorization required' });
}
const token = authorization.split(' ')[1];
try {
const { _id } = jwt.verify(token, process.env.SECRETE);
req.user = await User.findOne({ _id }).select('_id');
if (!req.user) {
return res.status(401).json({ error: 'User not found' });
}
next();
} catch (error) {
console.error(error);
res.status(401).json({ error: 'Request is not authorized' });
}
};
module.exports = requireAuth;
here the home.js components which has GET METHOD
import { useEffect } from "react";
import Blogs from "../components/Blogs";
import { useBlogContext } from "../Hooks/useBlogContext";
import { useAuthContext } from "../Hooks/useAuthContext";
const Home = () => {
const { dispatch } = useBlogContext();
const user = useAuthContext()
useEffect(() => {
const fetchBlog = async () => {
const response = await fetch('/api/blog', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'authorization': `Bearer ${user.token}`
}
});
const json = await response.json();
if (response.ok) {
dispatch({ type: 'SET_BLOGS', payload: json });
}
};
fetchBlog();
}, [dispatch, user.token]);
return (
<div className="Home">
<div className="Home-container">
<h1>RetroBlog</h1>
<p>Where you can create, update, and show ideas</p>
</div>
<h1>All Recent Blogs</h1>
<Blogs />
</div>
);
};
export default Home;
I needed it to fetch data correctly from the database
error
JsonWebTokenError: jwt malformed
at module.exports [as verify] (F:Retro BlogBackendnode_modulesjsonwebtokenverify.js:70:17)
at requireAuth (F:Retro BlogBackendMiddlewarerequireAuth.js:15:29)
at Layer.handle [as handle_request] (F:Retro BlogBackendnode_modulesexpresslibrouterlayer.js:95:5)
at trim_prefix (F:Retro BlogBackendnode_modulesexpresslibrouterindex.js:328:13)
at F:Retro BlogBackendnode_modulesexpresslibrouterindex.js:286:9
at Function.process_params (F:Retro BlogBackendnode_modulesexpresslibrouterindex.js:346:12)
at next (F:Retro BlogBackendnode_modulesexpresslibrouterindex.js:280:10)
at Function.handle (F:Retro BlogBackendnode_modulesexpresslibrouterindex.js:175:3)
at router (F:Retro BlogBackendnode_modulesexpresslibrouterindex.js:47:12)
at Layer.handle [as handle_request] (F:Retro BlogBackendnode_modulesexpresslibrouterlayer.js:95:5)
M. ARUN is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.