Handling POST Requests with Express
Nội Dung Chính
Handling POST Requests with Express
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;
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();
app.use(express.json());
app.post('*'
, (req, res) => {
req.body;
res.json(req.body);
});
const
server = await
app.listen(3000
);
const
axios = require
('axios'
);
const
res = await
axios.post('http://localhost:3000/'
, {
answer
: 42
});
res.data;
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;
res.json(req.body);
});
const
server = await
app.listen(3000
);
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;
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();
form.parse(req, function
(err, fields, files
) {
if
(err != null
) {
console
.log(err)
return
res.status(400
).json({ message
: err.message });
}
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!