Express 4: Parse JSON body
Run npm install express
to install Express.
To parse the body of a request, we will need to use the body-parser
package that is included with Express. In this case we will accept JSON bodies from POST
requests and log it to our console.
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
// Port server listens on
const PORT = 8080;
// Set up Express application
const app = express();
app.use(bodyParser.json());
app.post('/', postHandler);
// Create HTTP server
http.createServer(app).listen(PORT, () => {
console.log(`listening on ${PORT}...`);
});
// Sends 202 response and logs body
function postHandler(req, res) {
console.log(JSON.stringify(req.body));
res.status(202).end();
}