skip to Main Content

I’m building a simple blog app using Express.js, and I’ve encountered an issue with the POST request body being undefined when I try to log it in the console:

console.log(req.body) // undefined

This is the code for my server.js file:

const express = require("express");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const jsonfile = require("jsonfile");

const app = express();
const PORT = process.env.PORT || 3000;
const file = "./db/blogs.json";

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

app.use(bodyParser.json());
app.use(express.static("public"));
app.use(morgan("dev"));

app.get("/", async (req, res) => {
  try {
    const data = await jsonfile.readFile(file);
    res.render("index.ejs", { title: "Home", blogs: data });
  } catch (err) {
    console.log(err);
    res.status(500).render("sr.ejs", { title: "Server Error" });
  }
});

app.get("/new", (req, res) => {
  res.render("new.ejs", { title: "Create New Blog" });
});

///////////////
app.post("/new-blog/", async (req, res) => {
  // console.log(req.body) // undefined
  try {
    const blog = {
      title: req.body.title,
      author: req.body.author,
      content: req.body.content,
    };
    const data = await jsonfile.readFile(file);
    data.push(blog);
    await jsonfile.writeFile(file, data);
    res.redirect("/");
  } catch (err) {
    console.log(err);
    res.status(500).render("sr.ejs", { title: "Server Error" });
  }
});
///////////////

app.get("/about", (req, res) => {
  res.render("about.ejs", { title: "About Us" });
});

app.use((req, res) => {
  res.render("nf.ejs", { title: "Page Not Found" });
});

process.on("uncaughtException", (err) => {
  console.log("UNCAUGHT ERROR:", err);
  process.exit(1);
});

I don’t see any problems in the HTML either:

<main class="form-container">
    <form action="/new-blog/" method="post">
      <div>
        <label for="author">Author</label>
        <input
          id="author"
          name="author"
          type="text"
          placeholder="bobby8"
          required
          autocomplete="off"
        >
      </div>
      <div>
        <label for="title">Title</label>
        <input
          id="title"
          name="title"
          type="text"
          placeholder="My Favorite Movie"
          required
          autocomplete="off"
        >
      </div>
      <div>
        <label for="content">Content</label>
        <textarea
          id="content"
          name="content"
          type="text"
          placeholder="It has to be..."
          required
          autocomplete="off"
        ></textarea>
      </div>
      <button type="submit">Post Blog</button>
    </form>
  </main>

The app doesn’t crash, but submitting more blogs just pushes more empty objects into the blogs.json file. I’ve already included body-parser middleware to parse JSON data, so I’m not sure what’s causing this issue.

Any suggestions on how to fix this small bug? Thanks!

Edit: Code is here – https://notepad.link/code/QAAbZenzG5KvX8C6Yg2J

2

Answers


  1. app.use(bodyParser.json()); is telling express to expect request body in json format. In your view, the form is sending data in application/x-www-form-urlencoded (the default) so I suspect you just have to remove that configuration or post data in json format with your form.

    Login or Signup to reply.
  2. app.use(express.urlencoded({ extended: false }));

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search