Kodokon kodokon.com

Serving content

Serve static files, handle HTML forms, and accept simple uploads with multer.

9 min · 3 questions

Open this lesson in Kodokon

An API doesn't only return JSON. HTML pages, images, stylesheets, a front-end build: Express serves all of it with a single middleware, express.static. Each file in the folder becomes accessible at the matching URL: public/logo.png responds on /logo.png.

JAVASCRIPT
import express from "express";

const app = express();

app.use(express.static("public"));

app.listen(3000, () => {
  console.log("http://localhost:3000");
});

Let's move on to forms. A classic HTML form sends its fields in the application/x-www-form-urlencoded format. The express.urlencoded middleware decodes them and fills req.body, exactly like express.json does for JSON. Place a page in public/ containing a form with method set to POST and action set to /contact, then handle the submission:

JAVASCRIPT
app.use(express.urlencoded({ extended: true }));

app.post("/contact", (req, res) => {
  const { name, message } = req.body;
  if (!name || !message) {
    return res.status(400).send("Required fields");
  }
  res.send("Thank you " + name + ", message received.");
});

To send a file, the form must declare enctype with the value multipart/form-data and contain an input field of type file, named for example avatar. Express can't decode this format on its own: the reference middleware is multer.

BASH
npm install multer
JAVASCRIPT
import multer from "multer";

const upload = multer({
  dest: "uploads/",
  limits: { fileSize: 2 * 1024 * 1024 }
});

app.post(
  "/avatar",
  upload.single("avatar"),
  (req, res) => {
    if (!req.file) {
      return res.status(400).json({
        error: "No file received"
      });
    }
    res.status(201).json({
      name: req.file.filename,
      size: req.file.size
    });
  }
);
Size capped at 2 MB by the limits property

Knowledge check

Make sure you remember the key points of this lesson.

  1. What does express.static do when applied to the public folder?
    • It serves each file in the folder at the matching URL
    • It compiles the folder's files at startup
    • It protects the folder with a password
  2. Which middleware fills req.body for a classic HTML form?
    • express.json()
    • express.urlencoded()
    • express.static()
  3. Which attribute must the form carry to send a file?
    • method set to GET
    • enctype set to multipart/form-data
    • target set to _blank