InterviewSolution
| 1. |
How to Redirect 404 errors to a Page in Express.js? |
|
Answer» We need to show errors or the well-known 404 page to users who go to a non-existent page in our website. We will learn to do that next. We will first go through the basic setup to create a new Node.js application by CREATING a directory and changing to it. Then will initialize a package.json file with the NPM init -y command. If we don’t specify the -y flag, we need to hit enter to a lot of default fields. Next, we will make it an EXPRESS app by adding the express package through npm. Now, we will create a file server.js in the root directory. Here, we are first doing the import for express and then using it in the app. Now, we have three routes here, first for the home and second for contact. The third one contains ‘*’ and it contains all the routes not present in the first two. If a user tries to go to some route which is not mentioned, they will be shown ‘Page not Found’. One thing to keep in mind, is that this wildcard(‘*’) route, should always be the last route in our code. Lastly, we are listening to all client requests on port 3000. Now, start the server by giving node server.js in the terminal. Now, if we go to any route except / or /contact, we will be shown the ERROR message. |
|