如果在我的服务器中找不到路径,我将尝试生成自定义错误

I am trying to make custom errors if a path is not found in my server

我的app.js代码。

// To make it clear to the consumer that the application is an API, prefix the endpoint with /api
app.use("/api/v1", auth);
app.use("/api/v1/pages", authRoute, pages);
app.use("/api/v1/users",authRoute, users);
app.use("/api/v1/books",authRoute, books);
app.use("/api/v1/authors",authRoute, authors);
app.use("/api/v1/chapters", authRoute, chapters);

const start = async () => {
  try {
    await conn(process.env.MONGO_URI); // Access the connection string in .env
    app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));
  } catch (err) {
    console.log(err);
  }
};

//rate limit 
const limit = rateLimit({
  windowMs: 1 * 60 * 1000,
  max: 25,
});

app.use(limit);

start();

export default app;

所以如果用户输入 /api/v1/bookkks 我想 return 一条消息说不存在。

如果输入错误,我目前会在邮递员中收到。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot GET /api/v1/chapter</pre>
</body>

</html>

请注意,这是一个 API,我没有设置任何网页。

您可以使用 Express 中的简单中间件来实现此目的。

看下面的补充,(404中间件必须是应用中最后定义的路由)

// To make it clear to the consumer that the application is an API, prefix the endpoint with /api
app.use("/api/v1", auth);
app.use("/api/v1/pages", authRoute, pages);
app.use("/api/v1/users", authRoute, users);
app.use("/api/v1/books", authRoute, books);
app.use("/api/v1/authors", authRoute, authors);
app.use("/api/v1/chapters", authRoute, chapters);

app.use((req, res, next) => {
  res.status(404).send("Route Not Found!");
});

const start = async () => {
  try {
    await conn(process.env.MONGO_URI); // Access the connection string in .env
    app.listen(PORT, () => console.log(`Server is listening on port ${PORT}`));
  } catch (err) {
    console.log(err);
  }
};