为 url 中的参数获取 400 错误请求错误

时间:2021-01-16 15:23:43

标签: reactjs express mongoose fetch bad-request

我正在尝试从数据库中获取数据它在邮递员中工作正常,但在本地主机上运行时抛出错误 获取所有学生的后端路线 用户需要登录、验证和管理员

// 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 未定义

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为您的问题出在前端。您确定要将 private Socket openTLSTunnel(String host) throws IOException { String raw_request = "CONNECT " + host + ":80 HTTP/1.1\n" + "Host: " + host + ":80" + "\r\n\r\n"; // Make a connection to the website. Socket tunnel = new Socket(); int timeout = 10000; var server = new InetSocketAddress(host, 80); tunnel.connect(server, timeout); // Write the request to server. OutputStream out = tunnel.getOutputStream(); byte[] msg = raw_request.getBytes(StandardCharsets.UTF_8); out.write(msg); out.flush(); // TODO send error to client. // Get the response from server. InputStream in = tunnel.getInputStream(); byte reply[] = new byte[200]; int replyLen = 0; int newlinesSeen = 0; boolean headerDone = false; while (newlinesSeen < 2) { int i = in.read(); if (i < 0) { throw new IOException("Unexpected EOF from proxy"); } if (i == '\n') { headerDone = true; ++newlinesSeen; } else if (i != '\r') { newlinesSeen = 0; if (!headerDone && replyLen < reply.length) { reply[replyLen++] = (byte) i; } } } String replyStr = new String(reply, 0, replyLen, "ASCII7"); // Check if connection established. if(!replyStr.toLowerCase().contains("200 connection established")) { System.out.println("No TLS connection established!"); throw new AccessDeniedException(replyStr); } else{ System.out.println("Connection established!"); } return tunnel; } 传递给 userId 函数吗?因为从您的网络结果来看,您似乎忘记将任何参数传递给该函数。如果您在调用该函数的地方共享代码,会更容易回答。

相关问题