Express JS - post method - req.body is getting undefined even I use app.use(express.json())

Viewed 32

my code is like this -

const express = require("express");
const path = require("path");
const { open } = require("sqlite");
const sqlite3 = require("sqlite3");

const dbPath = path.join(__dirname, "moviesData.db");

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

let database = null;

const initializeDBAndServer = async () => {
  try {
    database = await open({
      filename: dbPath,
      driver: sqlite3.Database,
    })
    app.listen(5353, () => {
      console.log(`server is running at http://localhost:5353/`)
    })
  } catch (error) {
    console.log(`error: ${error.message}`);
    process.exit(1)
  }
}

initializeDBAndServer();

app.post("/myId", async (req, res) => {
  const { id } = req.body;
  console.log(`requested Id is ${id}`);
  res.send(`requested Id id ${id}`);
})

my request is -

POST http://localhost:5353/myId/
Content-Type: "application/json"

{
  "id": 123456 
}

And the console and response is coming the same

requested Id is undefined

I have used - app.use(express.json()). It is not working. And also installed body-parser and also tried. It also not worked.

So, please help me out by giving the correct code.

1 Answers

The Content-Type in your request is incorrect, it should be application/json, not "application/json":

Content-Type: application/json
Related