Handle POST Form Data with Express JS
Jan 10, 2022
Express doesn't handle FormData instances by default. FormData is useful for tasks like uploading a file. You need to use a separate FormData parser, like Formidable, as shown below.
const formidable = require('formidable');
app.post('/upload', function(req, res) {
const form = new formidable.IncomingForm();
// Parse `req` and upload all associated files. `files` contains
// all files that were uploaded with the form.
form.parse(req, function(err, fields, files) {
if (err) {
return res.status(400).json({ error: err.message });
}
const [firstFileName] = Object.keys(files);
res.json({ filename: firstFileName });
});
});
Built an Express app and want to deploy it?
We recommend Railway. It lets you deploy Node.js and Express apps without dealing with servers, Docker, CI/CD pipelines, or infrastructure. Click button, select GitHub repo, get URL. We've been using Railway for years to spin up apps quickly.
Deploy your Express app on Railway in minutes
We recommend Railway. It lets you deploy Node.js and Express apps without dealing with servers, Docker, CI/CD pipelines, or infrastructure. Click button, select GitHub repo, get URL. We've been using Railway for years to spin up apps quickly.
Deploy your Express app on Railway in minutes
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!