Search code examples
typescriptexpressbody-parser

ExpressJS body-parser is not working, it is empty in post request


I created a server using express.js, body-parser with typescript like following.

app.ts

import express, { Application, Request, Response } from 'express';
import morgan from 'morgan';
import bodyParser from 'body-parser';
// import Router from './routes';
import cors from 'cors';

const app: Application = express();

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morgan('tiny'));
// app.use('/api', Router);
app.post('/test', (req: Request, res: Response) => {
    console.log("req.body => ", req.body)
    res.send(req.body)
})

export default app;

index.ts

import app from './app';
import * as dotenv from 'dotenv';
dotenv.config();

app.listen(process.env.PORT, () => {
  // tslint:disable-next-line: no-console
  console.log(`HTTP Server successfully started at port ${process.env.PORT}`);
});

.env

PORT=8080

package.json

...
"scripts": {
    "start": "node build/index.js",
    "build": "tsc",
    "dev": "cross-env NODE_ENV=development && nodemon",
    ...
},
"devDependencies": {
    "@types/cors": "^2.8.10",
    "@types/express": "^4.17.8",
    "@types/jest": "^29.5.3",
    "@types/morgan": "^1.9.1",
    "@types/node": "^14.17.7",
    "@types/supertest": "^2.0.12",
    "jest": "^26.6.3",
    "nodemon": "^2.0.15",
    "sequelize-cli": "^6.2.0",
    "supertest": "^6.3.3",
    "ts-jest": "^26.4.4",
    "ts-node": "^10.1.0",
    "tslint": "^6.1.3",
    "typescript": "^4.0.3"
  },
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "cross-env": "^7.0.3",
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "morgan": "^1.10.0",
    ...
  },
...
}

I sent request using Postman.

// header
Content-Type: application/json

// endpoint
POST http://localhost:8080/test

// body
{
    "title": "Testing",
    "description": "I am testing server."
}

The backend console's result is

req.body => {}

It should be req.body => { "title": "Testing", "description": "I am testing server." }, but it is empty.
I tried to solve this problem for about 2 hours.


Solution

  • I updated app.ts like this. It works.

    import express, { Application, Request, Response } from 'express';
    import morgan from 'morgan';
    import bodyParser from 'body-parser';
    // import Router from './routes';
    import multer from 'multer';
    import cors from 'cors';
    
    const app: Application = express();
    const upload = multer()
    
    app.use(cors());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.use(upload.none()); 
    app.use(morgan('tiny'));
    // app.use('/api', Router);
    app.post('/test', (req: Request, res: Response) => {
        console.log("req.body => ", req.body)
        res.send(req.body)
    })
    
    export default app;
    

    I installed multer. It works with form-data.