【发布时间】:2021-04-21 09:02:17
【问题描述】:
我正在尝试从数据库中获取数据它在邮递员中工作正常,但是当我在本地主机上运行它时抛出错误 获取所有学生的后端路线 用户需要登录、认证和管理员
// listng route
router.get(
"/students/:userId",
isSignedIn,
isAuthenticated,
isAdmin,
getAllStudents
);
后端处理请求的控制器
exports.getAllStudents = (req, res) => {
let sortBy = req.query.sortBy ? req.query.sortBy : "_id";
let limit = req.query.limit ? parseInt(req.query.limit) : 8;
Student.find()
.select("-address")
.populate("faculty")
.sort([[sortBy, "asc"]])
.limit(limit)
.exec((err, students) => {
if (err) {
return res.status(400)({
error: "No students found",
});
}
res.json(students);
});
};
上面的代码在邮递员上可以正常工作,但是当我将它与前端连接时,它会出现以下错误
**Fetching API calls atb frontend**
export const getAllStudents = (userId, token) => {
return fetch(`${API}/students/${userId}`, {
method: "GET",
headers: {
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
})
.then((response) => {
console.log("res :", response);
return response.json();
})
.catch((err) => console.log(err));
};
前端路由
<AdminRoutes path="/admin/students" exact component={ManageStudents} />
错误 - 它说 ${userId} id 未定义
【问题讨论】:
标签: reactjs express mongoose fetch bad-request