My server creation process involved using express.js
, body-parser
, and typescript
. Here is a snippet of the code:
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",
...
},
...
I made a request using Postman.
// header
Content-Type: application/json
// endpoint
POST http://localhost:8080/test
// body
{
"title": "Testing",
"description": "I am testing server."
}
The response from the backend's console was
req.body => {}
Expected result should be
req.body => { "title": "Testing", "description": "I am testing server." }
, but it came out empty.I spent approximately 2 hours trying to troubleshoot this issue.