Handling POST Requests with Express

Feb 23, 2021

Express makes it easy to register route handlers for POST requests. Here's a basic POST request handler.

const express = require('express');

const app = express();

app.post('/', function requestHandler(req, res) {
  res.end('Hello, World!');
});

const server = await app.listen(3000);

The above code starts an Express server on port 3000 that handles POST requests to the / endpoint. You can then send requests to the server using an HTTP client like Axios

const data = await axios.post('http://localhost:3000/', {}).then(res => res.data);
data; // 'Hello, World!'

JSON Request Bodies

POST requests requests are different from GET requests because POST requests are allowed to send data in the HTTP request body. For example, the below code sends an HTTP POST request with a JSON object in the request body:

const axios = require('axios');
const res = await axios.post('http://localhost:3000/', {
  answer: 42
});

Express doesn't parse HTTP request bodies by default, but it does have a built-in middleware that populates the req.body property with the parsed request body. For example, app.use(express.json()) is how you tell Express to automatically parse JSON request bodies for you.

const express = require('express');
const app = express();

// Parse JSON bodies for this app. Make sure you put
// `app.use(express.json())` **before** your route handlers!
app.use(express.json());

app.post('*', (req, res) => {
  req.body; // JavaScript object containing the parse JSON
  res.json(req.body);
});
const server = await app.listen(3000);

// Demo showing the server in action
const axios = require('axios');
const res = await axios.post('http://localhost:3000/', {
  answer: 42
});
res.data; // `{ answer: 42 }`

URL Encoded Request Bodies

Express has an officially supported module body-parser that includes a parser for URL-encoded request bodies, like the ones submitted by HTML forms.

const express = require('express');
const app = express();
app.use(require('body-parser').urlencoded({ extended: false }));
app.post('*', (req, res) => {
  req.body; // { answer: 42 }
  res.json(req.body);
});
const server = await app.listen(3000);

// Demo of making a request with a URL-encoded body.
const axios = require('axios');
const headers = {
  'Content-Type': 'application/x-www-form-urlencoded'
};
const res = await axios.
  post('http://localhost:3000/', 'answer=42', { headers });

res.data; // { answer: 42 }

File Uploads

POST requests are often used for file uploads. Express itself doesn't make it easy to upload files, but there are several npm modules that handle file uploads for you. Formidable is the most popular file uploading library for Express. Here's how you can use Formidable to upload files:

const app = require('express')();
const formidable = require('formidable');
const fs = require('fs');

app.post('/upload', function(req, res) {
  const form = new formidable.IncomingForm();
  // Parse `req` and upload all associated files
  form.parse(req, function(err, fields, files) {
    if (err != null) {
      console.log(err)
      return res.status(400).json({ message: err.message });
    }

    // The `files` object contains all files that were uploaded. Formidable
    // parses each file and uploads it to a temporary file for you.
    const [firstFileName] = Object.keys(files);

    res.json({ filename: firstFileName });
  });
});

const server = await app.listen(3000);

Want to become your team's Express expert? There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called Espresso. Get your copy!

Espresso supports:
  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require('cors')())`
  • Express 4.0 style subrouters
As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Express Tutorials