JsonWebTokenError: login working but CRUD not Working



我为一个电子商务web应用程序的示例项目编写了一个代码。一切都很好,如登录,注册,管理仪表板。从api读取是完美的工作。每个受保护的管理路由在POSTMAN下都工作得很好。. 但是每当我尝试从前端创建、更新或删除产品时,它都会抛出如下错误。请帮我解决

JsonWebTokenError:必须提供jwt[0] at module。exports [as verify] (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesjsonwebtokenverify.js:60:17)[0] at requireSignIn (file:///C:/Users/Bangladesh%20One/Desktop/ReactJs/eCommerceApp/middleware/authMiddleware.js:8:24)[0] at Layer。handle [as handle_request] (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterlayer.js:95:5)[0] at next (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterroute.js:144:13)[0] [au:]调度(C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterroute.js:114:3)[0] at Layer。handle [as handle_request] (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterlayer.js:95:5)[0] at C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterindex.js:284:15[0] at Function。process_params (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterindex.js:346:12)[0] at next (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterindex.js:280:10)[0] at Function。handle (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterindex.js:175:3)

我尝试与邮差如果我的管理路线工作良好,我得到了积极的结果邮差。但每当我尝试创建,更新,删除带有前端的产品时,它都会抛出错误。但登录,注册工作正常

这是我的中间件

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",
});
}
};

我的创建类别前端代码在这里

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;

看起来您没有将JWT从前端代码发送到后端代码。您需要在每个中设置authorization标头。(至少在执行requireSignIn中间件的每个请求中)。

要在axios中添加标题,请参考此。一种方法是在每个axios请求中添加header -

确保将jwt存储在本地存储中参考-如何获取/设置本地存储项目和如何在浏览器中查看本地存储项目

// Replace jwt with the variable name that you used to set the token
const token = localStorage.getItem("jwt");
axios.get('sampleURL', {
headers: {
Authorization: token
}
})
// for post/put etc
axios.post('sampleURL', {
name: updatedName 
},
{
headers: {
Authorization: token
}
})

另一种简单的方法是使用Axios拦截器。这将在发送到后端服务器之前为所有请求添加一个报头,从而节省了每次手动发送请求时插入报头的工作量。

在你的app.js中-

axios.interceptors.request.use(function (config) {
// Intercept the request and set the token before sending it to backend
const token = localStorage.getItem("jwt"); 
config.headers.Authorization =  token;
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});

您在注释中提到的错误看起来像是括号和逗号的语法问题。请确保axios请求中的头/数据前没有遗漏任何逗号,并且语法正确。

相关内容

  • 没有找到相关文章

最新更新