The route is an important component of a website. It helps the website know where the user is going to the website, thereby responding appropriately.
In Express, routes are built-in and easy to use. In this article, let’s learn about routes in Express.
Routing in Node.js determines how the application will respond when a user makes a request to a particular endpoint.
That endpoint is usually a URI or a path (Path) with a specific request method (POST, PUT, GET, DELETE)
In express.js, routing has the following structure.
app.METHOD(Path, Handler...)
Example
app.get("/hello", (req, res) => {
res.send("Hello World");
});
Within a route, we can do anything, such as:
Express also has a router, so we can store routes in separate files and make our codes cleaner.
Note
Express supports many HTTP methods, and GET, POST, PUT, DELETE are the most used.
// respond with "Hello World!" on the homepage
app.get("/", function (req, res) {
res.send("Hello World!");
});
// accept POST request on the homepage
app.post("/", function (req, res) {
res.send("Got a POST request");
});
// accept PUT request at /user
app.put("/user", function (req, res) {
res.send("Got a PUT request at /user");
});
// accept DELETE request at /user
app.delete("/user", function (req, res) {
res.send("Got a DELETE request at /user");
});
With the above declaration, the server will send back a corresponding text when we access the address localhost:3000/user by GET, POST, PUT, and DELETE methods.
When we access /hello, then the route will match, and the function will be called.
Route paths can be strings, string patterns, or regular expressions.
/public/post
: is a regular path/public/user/*
: is a path with the symbol * representing any string/.*hello$/
: is a path in the form of a regex.Example 1: String pattern
The * symbol here means that the above route matches all paths starting with /users/.
app.get("/users/*", (req, res) => {
// Do something.
});
Example 2:
This is a path with a regular expression. This route will match any path ending with hello.
app.get(/.*hello$/, (req, res) => {
// Do something.
});
Route parameters are named URL segments that can retrieve the corresponding values.
// Get the user's info by id
app.get("/user/:id", (req, res) => {
let id = req.params["id"];
res.send("The id is " + id);
});
With the above declaration, when we access the address localhost:3000/user/125, the server will return the text: The id is 125.