Serve static files, handle HTML forms, and accept simple uploads with multer.
Open this lesson in KodokonAn 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.
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:
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.
npm install multerimport 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
});
}
);express.static do when applied to the public folder?req.body for a classic HTML form?express.json()express.urlencoded()express.static()method set to GETenctype set to multipart/form-datatarget set to _blank