I am developing a web app on MERN stack blog app, I have developed the backend API in render, frondend in vercel and they are working fine on postman and working fine in localhost. The problem is when I’m connecting backend with frontend and after giving a post request -adding a new comment to a post it failed with 401 anauthorized,its not working on deployment but working right at local machine. Whenever I’m running this it shows unauthorized 401 error. Here’s the code I don’t know what I’m doing wrong. What I could figure out from reading the error is that the problem is in auth some axios like error code, it shows error name as 401 unauthorized.
Here is the error image:-
enter image description here
This is my front end code
import { useNavigate, useParams } from "react-router-dom"
import Comment from "../components/Comment"
import Footer from "../components/Footer"
import Navbar from "../components/Navbar"
import {BiEdit} from 'react-icons/bi'
import {MdDelete} from 'react-icons/md'
import axios from "axios"
import { URL,IF } from "../url"
import { useContext, useEffect, useState } from "react"
import { UserContext } from "../context/UserContext"
const PostDetails = () => {
const postId=useParams().id
const [post,setPost]=useState({})
const {user}=useContext(UserContext)
const [comments,setComments]=useState([])
const [comment,setComment]=useState("")
// const [loader,setLoader]=useState(false)
console.log(postId)
const navigate=useNavigate()
const fetchPost=async()=>{
try{
const res= await axios.get(URL+"/api/posts/"+postId)
// console.log(res.data)
setPost(res.data)
}
catch(err){
console.log(err)
}
}
useEffect(()=>{
fetchPost()
},[postId])
// handle delete post
const handleDeletePost=async ()=>{
try{
const res=await axios.delete(URL+"/api/posts/"+postId,{withCredentials:true})
console.log(res.data)
navigate("/")
}
catch(err){
console.log(err)
}
}
useEffect(()=>{
fetchPost()
},[postId])
const fetchPostComments=async()=>{
// setLoader(true)
try{
const res=await axios.get(URL+"/api/comments/post/"+postId,{withCredentials:true})
setComments(res.data)
// setLoader(false)
}
catch(err){
// setLoader(true)
console.log(err)
}
}
useEffect(()=>{
fetchPostComments()
},[postId])
const postComment=async(e)=>{
e.preventDefault()
try{
const res=await axios.post(URL+"/api/comments/create",
{comment:comment,author:user.username,postId:postId,userId:user._id},
{withCredentials:true})
console.log(res.data)
fetchPostComments()
setComment("")
window.location.reload(true)
}
catch(err){
console.log(err)
}
}
return (
<div>
<Navbar/>
<br/>
<br/>
<br/>
<div className="px-8 md:px-[200px] mt-8">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold text-black md:text-3xl">{post.title}</h1>
<div className="flex items-center justify-center space-x-2">
<p className="cursor-pointer" onClick={()=>navigate("/edit/"+postId)}><BiEdit/></p>
<p className="cursor-pointer" onClick={handleDeletePost}><MdDelete/></p>
</div>
</div>
<div className="flex items-center justify-between mt-2 md:mt-4">
<p>@{post.username}</p>
<div className="flex space-x-2">
<p>{new Date(post.updatedAt).toString().slice(0,10)}</p>
<p>{new Date(post.updatedAt).toString().slice(16,24)}</p>
</div>
</div>
<img src={IF+post.photo} className="w-full mx-auto mt-8" alt=""/>
<p className="mx-auto mt-8">{post.desc}</p>
<div className="flex items-center mt-8 space-x-4 font-semibold">
<p>Categories:</p>
<div className="flex items-center justify-center space-x-2">
{post.categories?.map((c,i)=>(
<>
<div key={i} className="px-3 py-1 bg-gray-300 rounded-lg">{c}</div>
</>
))}
</div>
</div>
<div className="flex flex-col mt-4">
<h3 className="mt-6 mb-4 font-semibold">Comments:</h3>
{/* comment */}
{comments?.map((c)=>(
<Comment key={c._id} c={c} post={post} />
))}
</div>
{/* write a comment */}
<div className="flex flex-col mt-4 md:flex-row">
<input onChange={(e)=>setComment(e.target.value)} type="text" placeholder="write a comment" className="md:w-[90%] outline-none px-4 mt-4 md:mt-0"/>
<button onClick={postComment} className="bg-black text-sm text-white px-2 py-2 md:w-[20%] mt-4 md:mt-0">Add Comment</button>
<br/>
</div>
</div>
<Footer/>
</div>
)
}
export default PostDetails
This is my backend API file
where CREATE is the func. not working on deploy
const express=require('express')
const router = express.Router();
const User=require('../models/User')
const bcrypt=require('bcrypt')
const Post=require('../models/Post')
const Comment=require('../models/Comment');
const verifyToken = require('../verifyToken');
//CREATE
router.post("/create",verifyToken,async(req,res)=>{
try{
const newComment=new Comment(req.body)
const savedComment=await newComment.save()
res.status(200).json(savedComment)
}
catch(err){
res.status(200).json(err)
}
})
//UPDATE
router.put("/:id",verifyToken,async (req,res)=>{
try{
const updatedComment=await Comment.findByIdAndUpdate(req.params.id,{$set:req.body},{new:true})
res.status(200).json(updatedComment)
}
catch(err){
res.status(500).json(err)
}
})
//DELETE
router.delete("/:id",verifyToken,async (req,res)=>{
try{
await Comment.findByIdAndDelete(req.params.id)
res.status(200).json("Comment has been deleted!")
}
catch(err){
res.status(500).json(err)
}
})
//GET POST COMMENT
router.get("/post/:postId",async (req,res)=>{
try{
const comments=await Comment.find({postId:req.params.postId})
res.status(200).json(comments)
}
catch(err){
res.status(500).json(err)
}
})
module.exports=router
this is my model code:-
const mongoose=require('mongoose')
const CommentSchema=new mongoose.Schema({
comment:{
type:String,
required:true,
},
author:{
type:String,
required:true,
},
postId:{
type:String,
required:true,
},
userId:{
type:String,
required:true
}
},{timestamps:true})
module.exports=mongoose.model("Comment",CommentSchema)
this is my server api code :-
const express=require('express')
const app=express()
const mongoose=require('mongoose')
const dotenv=require('dotenv')
const cors=require('cors')
const path=require("path")
const multer=require('multer')
const cookieParser=require('cookie-parser')
const authRoute=require('./routes/auth')
const userRoute=require('./routes/users')
const postRoute=require('./routes/posts')
const commentRoute = require("./routes/comment")
const ottRoute=require('./routes/ott')
const releaseRoute=require('./routes/release')
const responseRoute=require('./routes/response');
const ratingRoute=require('./routes/rating')
//database
const connectDB=async()=>{
try{
await mongoose.connect(process.env.MONGO_URL)
console.log("database is connected successfully!")
}
catch(err){
console.log(err)
}
}
//middlewares
dotenv.config()
app.use(express.json())
app.use("/images",express.static(path.join(__dirname,"/images")))
app.use(cors({ origin: "http://localhost:5173", credentials: true }));
app.use(cookieParser())
app.use("/api/auth",authRoute)
app.use("/api/users",userRoute)
app.use("/api/posts",postRoute)
app.use("/api/comments", commentRoute)
app.use("/api/otts",ottRoute);
app.use("/api/releases",releaseRoute)
app.use("/api/responses",responseRoute)
app.use("/api/rating",ratingRoute)
//image upload
const storage=multer.diskStorage({
destination:(req,file,fn)=>{
fn(null,"images")
},
filename:(req,file,fn)=>{
fn(null,req.body.img)
// fn(null,"image1.jpg")
}
})
const upload=multer({storage:storage})
app.post("/api/upload",upload.single("file"),(req,res)=>{
res.status(200).json("Image has been uploaded successfully!")
})
app.listen(process.env.PORT,()=>{
connectDB()
console.log("app is running on port "+process.env.PORT)
})
and this is my verifyToken code:-
const jwt=require('jsonwebtoken')
const verifyToken=(req,res,next)=>{
const token=req.cookies.token
console.log(token)
if(!token){
return res.status(401).json("You are not authenticated!")
}
jwt.verify(token,process.env.SECRET,async (err,data)=>{
if(err){
return res.status(403).json("Token is not valid!")
}
req.userId=data._id
console.log("passed")
next()
})
}
module.exports=verifyToken
For Referances:-
my backend gitcode
my frontend gitcode
I am trying to deploy my learning mern blog app project which is working in local machine. I need to host it such that able to perform Whole CRUD operations as in localhost.