InterviewSolution
| 1. |
What is routing and how does it work in Express? |
|
Answer» Routing is the WAY in which the server responds to a CLIENTS request to a particular path, when it comes through different protocols like GET, POST, PUT, DELETE. In common words, it is the function which gets called then the user goes to a URL on the web-app. After that, install express in it through npm i express command. The basic routing is done through app.method(path, callback) function. In our example, we are using the get and the post methods. The app.get(), have a route to the root directory and just sends a TEXT back to the client browser. The app.post(), have a /submit route in which we are logging the plain text, which we will receive from the client browser. After that we are sending the ‘Data received Successfully’ message to the client browser. First start the server by GIVING node server.js in the terminal. Now, check the GET route go to http://localhost:3000/ from the browser and we will see the text Hello Express in it. The POST route requires a form to be submitted from the frontend, or we can do it from the postman app. Here, we are sending a plain text, because our server is expecting a plain text. Now, in the server logs also we are receiving the text, which we have sent. We can also use modular routes using express.router(), with which we can reuse a route. Create a new file router.js and add the below content in it. Here, we are using the router.route() to the same path. After that we have a .get() and .post() route.
Now, we will use the routes in the app.js file. Here, we are importing the router.js file and after that with app.use(), using it in different ways. Now, go to http://localhost:3000/dev/nabendu/22 and we will get the welcome text served from router.js file. We can also do a POST request from http://localhost:3000/tester/shikha/24 and we will get the Data received text served from router.js file. |
|