Express Get JSON Body
This is something that gets me everytime I’m setting up an Express app so I thought I would make a note here so I can (hopefully) remember this super simple thing for Express to get JSON body data.
If you’re setting up a new Express server that is going to be taking user input e.g. with a POST
, PATCH
or PUT
request and want to accept that input as JSON and Express JSON is not working then there’s one simple thing you need to add to your Express setup to ensure it can ‘read’ or ‘see’ this in the request
body.
You basically need to use the Express JSON parser (or rather the Express JSON middleware).
import express from 'express';
const app = express();
app.use(express.json()); // This what you want to add
app.listen(3000, () => {
console.log(`Listening at http://localhost:3000/`);
});
Then in your controller or routes file when you’re dealing with a request you can extract any JSON that’s sent in the request from the body.
import { Router } from "express";
const router = Router();
router.post('/', (request, response) => {
const { body } = request; // If 'body' is undefined you either haven't set up express.json()
// OR
// The request sent hasn't got the right headers e.g. application/json
return response.send(`Received Body: ${body}`);
});
export { router as myRoutes };
As mentioned in the notes above, the POST
request being made must have the right headers set (otherwise body
will still be undefined) but most front end network APIs (e.g. fetch
, axios
etc.) will do this automatically if you are sending an object.