hello guys there is issue in code i cannot get _id in require Auth method
here is an requireAuth code
<code>const jwt = require('jsonwebtoken');
const User = require('../models/userModel');
const requireAuth = async (req, res, next) => {
const { authorization } = req.headers;
return res.status(401).json({ error: 'Authorization required' });
const token = authorization.split(' ')[1];
const id = jwt.verify(token, process.env.SECRETE);
req.user = await User.findOne({ _id: id }).select('_id');
return res.status(401).json({ error: 'User not found' });
res.status(401).json({ error: 'Request is not authorized' });
module.exports = requireAuth;
<code>const jwt = require('jsonwebtoken');
const User = require('../models/userModel');
const requireAuth = async (req, res, next) => {
// Verify authentication
const { authorization } = req.headers;
if (!authorization) {
return res.status(401).json({ error: 'Authorization required' });
}
// Verify token
const token = authorization.split(' ')[1];
try {
const id = jwt.verify(token, process.env.SECRETE);
req.user = await User.findOne({ _id: 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;
</code>
const jwt = require('jsonwebtoken');
const User = require('../models/userModel');
const requireAuth = async (req, res, next) => {
// Verify authentication
const { authorization } = req.headers;
if (!authorization) {
return res.status(401).json({ error: 'Authorization required' });
}
// Verify token
const token = authorization.split(' ')[1];
try {
const id = jwt.verify(token, process.env.SECRETE);
req.user = await User.findOne({ _id: 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;
it is blog controller code and it is problem in the post method which the undefines(_id) the get the id from the require auth method
<code>const Blog = require('../Model/blogModel');
const mongoose = require('mongoose');
const getblogs = async (req, res) => {
const blogs = await Blog.find().sort({ createdAt: -1 });
res.status(200).json(blogs);
res.status(400).json({ error: error.message });
const getblog = async (req, res) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(404).json({ error: 'No such blog' });
const blog = await Blog.findById(id);
res.status(200).json(blog);
res.status(400).json({ error: error.message });
const postblog = async (req, res) => {
const { title, content, author, img_url, body } = req.body;
emptyfields.push('title');
emptyfields.push('content');
emptyfields.push('author');
emptyfields.push('img_url');
emptyfields.push('body');
if (emptyfields.length > 0) {
return res.status(400).json({ error: 'Please fill in all fields', emptyfields });
console.log(req.user._id)
const user_id = req.user._id;
const newblog = await Blog.create({ title, content, author, img_url, body, user_id });
res.status(200).json(newblog);
res.status(400).json({ error: error.message });
const deleteblog = async (req, res) => {
const { id } = req.params;
const blog = await Blog.findByIdAndDelete(id);
return res.status(404).json({ error: 'Blog not found' });
res.status(200).json(blog);
res.status(400).json({ error: error.message });
const Updateblog = async (req, res) => {
const { id } = req.params;
const { title, content, author, img_url, body } = req.body;
const updatedBlog = await Blog.findByIdAndUpdate(id, { title, content, author, img_url, body }, { new: true });
return res.status(404).json({ message: 'Blog not found' });
res.status(200).json(updatedBlog);
res.status(400).json({ error: error.message });
<code>const Blog = require('../Model/blogModel');
const mongoose = require('mongoose');
// Get blogs
const getblogs = async (req, res) => {
try {
const blogs = await Blog.find().sort({ createdAt: -1 });
res.status(200).json(blogs);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
// Get a single blog
const getblog = async (req, res) => {
const { id } = req.params;
try {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(404).json({ error: 'No such blog' });
}
const blog = await Blog.findById(id);
res.status(200).json(blog);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
// Post a new blog
const postblog = async (req, res) => {
const { title, content, author, img_url, body } = req.body;
const emptyfields = [];
if (!title) {
emptyfields.push('title');
}
if (!content) {
emptyfields.push('content');
}
if (!author) {
emptyfields.push('author');
}
if (!img_url) {
emptyfields.push('img_url');
}
if (!body) {
emptyfields.push('body');
}
if (emptyfields.length > 0) {
return res.status(400).json({ error: 'Please fill in all fields', emptyfields });
}
try {
console.log(req.user._id)
const user_id = req.user._id;
const newblog = await Blog.create({ title, content, author, img_url, body, user_id });
res.status(200).json(newblog);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
// Delete a blog
const deleteblog = async (req, res) => {
const { id } = req.params;
try {
const blog = await Blog.findByIdAndDelete(id);
if (!blog) {
return res.status(404).json({ error: 'Blog not found' });
}
res.status(200).json(blog);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
// Patch a blog
const Updateblog = async (req, res) => {
const { id } = req.params;
const { title, content, author, img_url, body } = req.body;
try {
const updatedBlog = await Blog.findByIdAndUpdate(id, { title, content, author, img_url, body }, { new: true });
if (!updatedBlog) {
return res.status(404).json({ message: 'Blog not found' });
}
res.status(200).json(updatedBlog);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
module.exports = {
getblogs,
getblog,
postblog,
deleteblog,
Updateblog
};
</code>
const Blog = require('../Model/blogModel');
const mongoose = require('mongoose');
// Get blogs
const getblogs = async (req, res) => {
try {
const blogs = await Blog.find().sort({ createdAt: -1 });
res.status(200).json(blogs);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
// Get a single blog
const getblog = async (req, res) => {
const { id } = req.params;
try {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(404).json({ error: 'No such blog' });
}
const blog = await Blog.findById(id);
res.status(200).json(blog);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
// Post a new blog
const postblog = async (req, res) => {
const { title, content, author, img_url, body } = req.body;
const emptyfields = [];
if (!title) {
emptyfields.push('title');
}
if (!content) {
emptyfields.push('content');
}
if (!author) {
emptyfields.push('author');
}
if (!img_url) {
emptyfields.push('img_url');
}
if (!body) {
emptyfields.push('body');
}
if (emptyfields.length > 0) {
return res.status(400).json({ error: 'Please fill in all fields', emptyfields });
}
try {
console.log(req.user._id)
const user_id = req.user._id;
const newblog = await Blog.create({ title, content, author, img_url, body, user_id });
res.status(200).json(newblog);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
// Delete a blog
const deleteblog = async (req, res) => {
const { id } = req.params;
try {
const blog = await Blog.findByIdAndDelete(id);
if (!blog) {
return res.status(404).json({ error: 'Blog not found' });
}
res.status(200).json(blog);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
// Patch a blog
const Updateblog = async (req, res) => {
const { id } = req.params;
const { title, content, author, img_url, body } = req.body;
try {
const updatedBlog = await Blog.findByIdAndUpdate(id, { title, content, author, img_url, body }, { new: true });
if (!updatedBlog) {
return res.status(404).json({ message: 'Blog not found' });
}
res.status(200).json(updatedBlog);
} catch (error) {
res.status(400).json({ error: error.message });
}
};
module.exports = {
getblogs,
getblog,
postblog,
deleteblog,
Updateblog
};
this the post form code:
<code>import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useBlogContext } from '../Hooks/useBlogContext';
import { useAuthContext } from '../Hooks/useAuthContext';
const CreateBlogs = () => {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [body, setBody] = useState('');
const [imgUrl, setImgUrl] = useState('');
const [error, setError] = useState(null);
const navigate = useNavigate();
const { dispatch } = useBlogContext();
const { user } = useAuthContext();
const handleClick = async (e) => {
const blog = { title, content, author: user.username, body, img_url: imgUrl };
const response = await fetch('/api/blog', {
body: JSON.stringify(blog),
'Content-Type': 'application/json',
'Authorization': `Bearer ${user.token}`
const json = await response.json();
dispatch({ type: 'CREATE_BLOG', payload: json });
console.log('New blog added', json);
<label>Blog Title:</label>
<input type="text" name="title" value={title} onChange={(e) => setTitle(e.target.value)} />
<label>Blog Content:</label>
<input type="text" name="content" value={content} onChange={(e) => setContent(e.target.value)} />
<label>Blog Author:</label>
<input type="text" name="author" value={user?.username || ''} readOnly />
<label>Blog Image(Url):</label>
<input type="url" name="img_url" value={imgUrl} onChange={(e) => setImgUrl(e.target.value)} />
<label>Blog Body:</label>
<textarea name="body" cols="100" rows="10" value={body} onChange={(e) => setBody(e.target.value)}></textarea>
<button type="submit" onClick={handleClick}>Add Blog</button>
{error && <div className="error">{error}</div>}
export default CreateBlogs;
<code>import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useBlogContext } from '../Hooks/useBlogContext';
import { useAuthContext } from '../Hooks/useAuthContext';
const CreateBlogs = () => {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [body, setBody] = useState('');
const [imgUrl, setImgUrl] = useState('');
const [error, setError] = useState(null);
const navigate = useNavigate();
const { dispatch } = useBlogContext();
const { user } = useAuthContext();
const handleClick = async (e) => {
e.preventDefault();
if (!user) {
navigate('/login');
return;
}
const blog = { title, content, author: user.username, body, img_url: imgUrl };
const response = await fetch('/api/blog', {
method: 'POST',
body: JSON.stringify(blog),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${user.token}`
}
});
const json = await response.json();
if (!response.ok) {
setError(json.error);
} else {
setTitle('');
setContent('');
setImgUrl('');
setBody('');
setError(null);
dispatch({ type: 'CREATE_BLOG', payload: json });
console.log('New blog added', json);
navigate('/');
}
};
return (
<div className="create">
<form>
<h1>Create New Blog</h1>
<label>Blog Title:</label>
<input type="text" name="title" value={title} onChange={(e) => setTitle(e.target.value)} />
<label>Blog Content:</label>
<input type="text" name="content" value={content} onChange={(e) => setContent(e.target.value)} />
<label>Blog Author:</label>
<input type="text" name="author" value={user?.username || ''} readOnly />
<label>Blog Image(Url):</label>
<input type="url" name="img_url" value={imgUrl} onChange={(e) => setImgUrl(e.target.value)} />
<label>Blog Body:</label>
<textarea name="body" cols="100" rows="10" value={body} onChange={(e) => setBody(e.target.value)}></textarea>
<button type="submit" onClick={handleClick}>Add Blog</button>
{error && <div className="error">{error}</div>}
</form>
</div>
);
}
export default CreateBlogs;
</code>
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useBlogContext } from '../Hooks/useBlogContext';
import { useAuthContext } from '../Hooks/useAuthContext';
const CreateBlogs = () => {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [body, setBody] = useState('');
const [imgUrl, setImgUrl] = useState('');
const [error, setError] = useState(null);
const navigate = useNavigate();
const { dispatch } = useBlogContext();
const { user } = useAuthContext();
const handleClick = async (e) => {
e.preventDefault();
if (!user) {
navigate('/login');
return;
}
const blog = { title, content, author: user.username, body, img_url: imgUrl };
const response = await fetch('/api/blog', {
method: 'POST',
body: JSON.stringify(blog),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${user.token}`
}
});
const json = await response.json();
if (!response.ok) {
setError(json.error);
} else {
setTitle('');
setContent('');
setImgUrl('');
setBody('');
setError(null);
dispatch({ type: 'CREATE_BLOG', payload: json });
console.log('New blog added', json);
navigate('/');
}
};
return (
<div className="create">
<form>
<h1>Create New Blog</h1>
<label>Blog Title:</label>
<input type="text" name="title" value={title} onChange={(e) => setTitle(e.target.value)} />
<label>Blog Content:</label>
<input type="text" name="content" value={content} onChange={(e) => setContent(e.target.value)} />
<label>Blog Author:</label>
<input type="text" name="author" value={user?.username || ''} readOnly />
<label>Blog Image(Url):</label>
<input type="url" name="img_url" value={imgUrl} onChange={(e) => setImgUrl(e.target.value)} />
<label>Blog Body:</label>
<textarea name="body" cols="100" rows="10" value={body} onChange={(e) => setBody(e.target.value)}></textarea>
<button type="submit" onClick={handleClick}>Add Blog</button>
{error && <div className="error">{error}</div>}
</form>
</div>
);
}
export default CreateBlogs;
this full code for the project is:
https://github.com/ArunM037/Retro_Blog-Using-Mern-Stack
the id from requireAuth needed to be defined i don’t what’s the problem