Search code examples
javascriptnode.jsexpresspostexpress-router

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


Here is my server.js code:

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...");
});

This code (which I commented) works fine

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

But when I try to do the same thing with router, it returns undefined. Here is my articles.js code from routes folder:

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;

Here id new.ejs code, where the from is:

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

The problem occurs only when I try to do this in router file. I would be very thankful if anyone can tell me what exactly am I doing wrong?


Solution

  • You need to use any router after using middlewares. I think using express.json() is required for parsing json from body of http request

    app.use(express.urlencoded({ extended: true }));
    app.use(express.json());
    // ... any middleware
    app.use("/articles", articleRouter);