Node.js | Basics of Request Handling with Express
Handling Query Strings
In Express, values passed in a query string are available from req.query. For example, when a page is accessed as /helo?name=devkuma, the value can be read as req.query.name and passed to an EJS template with res.render.
router.get("/", function(req, res, next) {
res.render("helo", {
title: "Hello",
message: "Hello, " + req.query.name
});
});
This is the simplest way to receive values sent through a URL. When using express-generator, routes are usually placed under routes/, and templates are placed under views/.
Receiving POST Forms
For values sent from an HTML form with method="post", define a POST handler with router.post. Express puts submitted form values into req.body.
router.post("/", function(req, res, next) {
res.render("helo", {
title: "Posted",
message: req.body.name + " / " + req.body.mail
});
});
The view can contain a form that posts back to the same route.
<form method="post" action="/helo">
<input type="text" name="name">
<input type="text" name="mail">
<input type="submit">
</form>
Use GET handlers for displaying forms and POST handlers for processing submitted values. This separation keeps request handling clear.
Returning Data for Ajax
Express can return plain text or JSON instead of rendering a template. res.send sends a response body directly, and res.json serializes an object as JSON.
router.get("/data", function(req, res, next) {
res.json({
name: "devkuma",
mail: "dev@example.com"
});
});
On the browser side, JavaScript can request this URL, parse the returned JSON, and update the page without reloading it. This is the basic pattern for Ajax access in an Express application.
Using Cookies
Cookies are available when the application uses cookieParser. Values can be written with res.cookie and read from req.cookies.
res.cookie("name", req.body.name);
var name = req.cookies.name;
Cookies are useful for keeping small pieces of client-specific state. The usual flow is to receive a value from a form, save it as a cookie, and then read it on later requests to customize the displayed page.