I write a code for a sample project of an ecommerce web application. Everything is working fine like login, registration, admin dashboard. Reading from api is perfectly working. Every protected admin route is working absolutely fine with POSTMAN. But whenever I try to create, update or delete a product from the frontend it throws a error as below. Please help me solve
JsonWebTokenError: jwt must be provided [0] at module.exports [as verify] (C:\Users\Bangladesh One\Desktop\ReactJs\eCommerceApp\node_modules\jsonwebtoken\verify.js:60:17) [0] at requireSignIn (file:///C:/Users/Bangladesh%20One/Desktop/ReactJs/eCommerceApp/middlewares/authMiddleware.js:8:24) [0] at Layer.handle [as handle_request] (C:\Users\Bangladesh One\Desktop\ReactJs\eCommerceApp\node_modules\express\lib\router\layer.js:95:5) [0] at next (C:\Users\Bangladesh One\Desktop\ReactJs\eCommerceApp\node_modules\express\lib\router\route.js:144:13) [0] at Route.dispatch (C:\Users\Bangladesh One\Desktop\ReactJs\eCommerceApp\node_modules\express\lib\router\route.js:114:3) [0] at Layer.handle [as handle_request] (C:\Users\Bangladesh One\Desktop\ReactJs\eCommerceApp\node_modules\express\lib\router\layer.js:95:5) [0] at C:\Users\Bangladesh One\Desktop\ReactJs\eCommerceApp\node_modules\express\lib\router\index.js:284:15 [0] at Function.process_params (C:\Users\Bangladesh One\Desktop\ReactJs\eCommerceApp\node_modules\express\lib\router\index.js:346:12) [0] at next (C:\Users\Bangladesh One\Desktop\ReactJs\eCommerceApp\node_modules\express\lib\router\index.js:280:10) [0] at Function.handle (C:\Users\Bangladesh One\Desktop\ReactJs\eCommerceApp\node_modules\express\lib\router\index.js:175:3)
I tried with POSTMAN if my admin routes are working fine and I got positive result with POSTMAN. But whenever I try to create, update, delete a product with frontend it throws error. But login , register is working fine
Here is my middleware
import JWT from "jsonwebtoken";
import userModel from "../models/userModel.js";
import asyncHandler from "express-async-handler"
//Protected Routes token base
export const requireSignIn = async (req, res, next) => {
try {
const decode = JWT.verify(
req.headers.authorization,
process.env.JWT_SECRET
);
req.user = decode;
next();
} catch (error) {
console.log(error);
}
};
//admin acceess
export const isAdmin = async (req, res, next) => {
try {
const user = await userModel.findById(req.user._id);
if (user.role !== 1) {
return res.status(401).send({
success: false,
message: "UnAuthorized Access",
});
} else {
next();
}
} catch (error) {
console.log(error);
res.status(401).send({
success: false,
error,
message: "Error in admin middelware",
});
}
};
My Create Category Frontend code is here
import React, { useEffect, useState } from "react";
import Layout from "../../component/Layout/Layout";
import AdminMenu from "../../component/Layout/AdminMenu";
import axios from "axios";
import CategoryForm from "../../component/Form/CategoryForm";
import { Modal } from "antd";
const CreateCategory = () => {
const [categories, setCategories] = useState([]);
const [name, setName] = useState("");
const [visible, setVisible] = useState(false);
const [selected, setSelected] = useState(null);
const [updatedName, setUpdatedName] = useState("");
//handle Form
const handleSubmit = async (e) => {
e.preventDefault();
try {
const { data } = await axios.post(
"http://localhost:8080/api/v1/category/create-category",
{
name
}
);
if (data?.success) {
alert(`${name} is created`);
getAllCategory();
} else {
alert(data.message);
}
} catch (error) {
console.log(error);
alert(data.message);
}
};
//get all cat
const getAllCategory = async () => {
try {
const { data } = await axios.get(
"http://localhost:8080/api/v1/category/get-category"
);
if (data.success) {
setCategories(data.category);
}
} catch (error) {
console.log(error);
alert("Something wwent wrong in getting catgeory");
}
};
useEffect(() => {
getAllCategory();
}, []);
//update category
const handleUpdate = async (e) => {
e.preventDefault();
try {
const { data } = await axios.put(
`http://localhost:8080/api/v1/category/update-category/${selected._id}`,
{ name: updatedName }
);
if (data.success) {
alert(`${updatedName} is updated`);
setSelected(null);
setUpdatedName("");
setVisible(false);
getAllCategory();
} else {
alert(data.message);
}
} catch (error) {
alert(data.message);
}
};
//delete category
const handleDelete = async (pId) => {
try {
const { data } = await axios.delete(
`http://localhost:8080/api/v1/category/delete-category/${pId}`
);
if (data.success) {
alert(`category is deleted`);
getAllCategory();
} else {
alert(data.message);
}
} catch (error) {
alert(data.message);
}
};
return (
<Layout title={"Dashboard - Create Category"}>
<div className="container-fluid m-3 p-3">
<div className="row">
<div className="col-md-3">
<AdminMenu />
</div>
<div className="col-md-9">
<h1>Manage Category</h1>
<div className="p-3 w-50">
<CategoryForm
handleSubmit={handleSubmit}
value={name}
setValue={setName}
/>
</div>
<div className="w-75">
<table className="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
{categories?.map((c) => (
<>
<tr>
<td key={c._id}>{c.name}</td>
<td>
<button
className="btn btn-primary ms-2"
onClick={() => {
setVisible(true);
setUpdatedName(c.name);
setSelected(c);
}}
>
Edit
</button>
<button
className="btn btn-danger ms-2"
onClick={() => {
handleDelete(c._id);
}}
>
Delete
</button>
</td>
</tr>
</>
))}
</tbody>
</table>
</div>
<Modal
onCancel={() => setVisible(false)}
footer={null}
open={visible}
>
<CategoryForm
value={updatedName}
setValue={setUpdatedName}
handleSubmit={handleUpdate}
/>
</Modal>
</div>
</div>
</div>
</Layout>
);
};
export default CreateCategory;