req.body returns 当我使用 express router 时未定义,即使我使用 express.urlencoded

req.body returns undefined when I use express router, even though I used express.urlencoded

这是我的 server.js 代码:

const express = require("express");
const articleRouter = require("./routes/articles");
const app = express();

app.set("view engine", "ejs");

app.use("/articles", articleRouter);

app.use(express.urlencoded({ extended: true }));

app.get("/", (req, res) => {
  const articles = [
    {
      title: "Test Article 1",
      createdAt: new Date(),
      description: "Test description 1",
    },
    {
      title: "Test Article 2",
      createdAt: new Date(),
      description: "Test description 2",
    },
  ];
  res.render("articles/index", { articles: articles });
});

// app.post("/articles", (req, res) => {
//   console.log(req.body);
// });

app.listen(3000, () => {
  console.log("Listening on port 3000...");
});

这段代码(我评论过的)工作正常

app.post("/articles", (req, res) => {
  console.log(req.body);
});

但是当我尝试用路由器做同样的事情时,它 returns 未定义。这是我来自路线文件夹的 articles.js 代码:

const express = require("express");
const router = express.Router();

router.get("/new", (req, res) => {
  res.render("articles/new");
});

router.post("/", (req, res) => {
  console.log(req.body);
});

module.exports = router;

这里是id new.ejs代码,其中发件人是:

<body>
  <div class="container">
    <h1 class="mb-4">New Article</h1>
    <form action="/articles" method="post">
      <%- include('_form_fields') %>
    </form>
  </div>
</body>

仅当我尝试在路由器文件中执行此操作时才会出现此问题。如果有人能告诉我我到底做错了什么,我将不胜感激?

使用中间件后需要使用任意路由器。 我认为需要使用 express.json() 来从 http 请求

的正文中解析 json
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// ... any middleware
app.use("/articles", articleRouter);

您应该将应用程序传递到路由器文件,然后像这样定期使用它:

 const articleRouter = require("./routes/articles");

 articleRouter(app);

articleRouter 文件中:

module.exports = (app) => {
    app.post("/", (req, res) => {
        console.log(req.body);
    });
}