【问题标题】:Getting 400 bad request error for params in urlurl 中的参数出现 400 错误请求错误
【发布时间】: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


    【解决方案1】:

    我认为您的问题出在前端。您确定将userId 传递给getAllStudents 函数吗?因为从您的网络结果来看,您似乎忘记将任何参数传递给该函数。如果您在启动对该函数的调用时共享代码会更容易回答。

    【讨论】:

    • 感谢您的帮助。我明白我的错误了。我没有将 userId 和令牌传递给函数,因此会发生错误。现在它可以正常工作了。
    猜你喜欢
    • 2019-07-17
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 2014-12-11
    相关资源
    最近更新 更多