Routing Operations in Express.js

Tags: Http Get Node.js Routing Http Post Http Delete Http All Express

Ftp Server Installation on Ubuntu Server

In this article, we will be evaluating the Routing mechanism used for schematizing the url structures, which is the most critical issue in all applications on the web platform, which is the most important element of user influence and is very important in terms of the legibility of search engines in terms of SEO, within the Express.js module of the Node.js framework.

As is known, there are four basic Http methods. These;

  1. GET
  2. POST
  3. PUT
  4. DELETE 

In addition to these basic http methods, there is also an "ALL" method in Express.js. This method has been created in a way that it can accommodate the functions of other methods alone to meet all incoming requests.

Routing routes are created using these methods in Express.js. Let's quickly illustrate this here, as we discussed in our previous articles.


const express = require("express");
const app = express();
 
app.get("/users", (request, response) => {
    response.send(`${request.url} : GET`);
}).post("/createuser", (request, response) => {
    response.send(`${request.url} : POST`);
}).put("/updateuser", (request, response) => {
    response.send(`${request.url} : PUT`);
}).delete("/removeuser", (request, response) => {
    response.send(`${request.url} : DELETE`);
});
 
app.listen(8000, () => {
    console.log("Hello Sir Node");
});

As you can see, route structures are created as above.

In the Express.js route configuration, we can further customize our routes with certain special characters. These characters are; "?", "*" And "+" are operators. Now if we examine these operators in order;

Node.js Routing Operators

"?" Node.js Routing Operator

"?" operator disables the character to the right of which is used.
For example;
If we take the value of "sirn? Ode", it will be possible even if there is an "n" character! although not!
"Sir? Node" = "sirnode" = "sirode"
If you want to use this operator on more than one character with a similar logic, it is enough to put the related expressions in parentheses.
"Sir (no) d" = "sirnode" = "sird"
The point to note here is that when working on more than one character, either not all of those characters will be in the expression or they will be all. In our last example, an error will be encountered in the "sird" expression based on this warning.

If we need to give a code example;

app.get("/use?rs", (request, response) => {
    response.send(`${request.url} : GET`);
});

"+" Node.js Routing Operator

The "+" operator is an operator that duplicates the same expression to the left of it.
For example;
In the "sir + node" expression, the "n" character can be duplicated and written as "sirrrr ... node".
Code example;

app.get("/use+rs", (request, response) => {
    response.send(`${request.url} : GET`);
});

The output can be : /useeeeers : GET

Assigning Parameters to GET Requests

In order to assign parameters in the form of Query String to the incoming GET requests, we define a variable as follows with the ":" operator.

app.get("/user/:id", (request, response) => {
    response.send(request.params);
});

The output : {"id":3}

 
Notice that we have defined a variable named "id" with the ":" operator. We can obtain the relevant variables and their values with the "request.params" command.
app.get("/user/:detail/:id", (request, response) => {
    response.send(`id : ${request.params.id} - detail : ${request.params.detail}`);
    console.log();
});

The output : id:3 - detail : profile

Route Management with Router Object

Gathering different route structures under a single class in our studies will present a rather complex and poorly manageable situation for the future. Therefore, dividing the route configurations into related modules and managing these modules as a whole via the Router object in Express.js will enable us to progress in our works very quickly and without any confusion.

Now let's take the subject over an example scenario. First, let's create our classes in which we will create more than one route structure.

//-user.js
  const express = require("express");
  const router = express.Router();
   
  router.get("/getusers", (request, response) => {
      response.send(`URL : ${request.url} | RequestType : GET`);
  }).post("/adduser", (request, response) => {
      response.send(`URL : ${request.url} | RequestType : POST`);
  });
  module.exports = router;
//-content.js
  const express = require("express");
  const router = express.Router();
   
  router.get("/getcontent", (request, response) => {
      response.send(`URL : ${request.url} | RequestType : GET`);
  }).post("/addcontent", (request, response) => {
      response.send(`URL : ${request.url} | RequestType : POST`);
  });
   
  module.exports = router;

If you pay attention to our classes, a route structure is created by using the "Router" method in the Express module and this route structure is transferred to other modules with the "module.exports". In order to use these route structures, they must be "required" to the relevant classes and introduced to the application with the "use" function as follows.

const express = require("express");
  const app = express();
  const userRoutes = require("./user");
  const contentRoutes = require("./content");
  app.use("/", userRoutes);
  app.use("/", contentRoutes);
   
  app.listen(8000, () => {
      console.log("Sir Node recommend Node.js");
  });

After this process, if we make requests to the relevant routes;

user.js --> getusers method's output : /getusers | RequestType : GET

user.js --> adduser method's output : /getusers | RequestType : POST

content.js --> getcontent method's output : /getcontent | RequestType : GET

content.js --> addcontent method's output : /addcontent | RequestType : POST

You will see that it works smoothly as in the examples.

Finally, according to the value of the first parameter given in the "use" function, the related route configurations will be called to be below the related value. Namely;

app.use("/user/", userRoutes);
  app.use("/content/", contentRoutes);

If it was defined as "user.js", urls in "user.js" would have to be created as "user / ****" and url in "content.js" would have to be created as "content / ****".