In this article I’m showing you how to redirect users using ExpressJS. First of all, when you want to redirect the user? Here are some real scenario.
Example, when user successfully login you can redirect him to the dashboard. Another instance, when user request for reset password, generally we generate an URL with user’s old password’s hash and send to user’s email. Here, I’m showing you How redirect user to dashboard after successfully login.
Client: Make a GET request on URL ‘/’ for login page. Server: Render login page Client: Next, user fill the form data and make a POST request on URL ‘/login’. Server: If user data matched then redirect to ‘/dashboaard/[ USER EMAIL ]’. Client: User make GET request on ‘/dashboaard/[ USER EMAIL ]’. Server: Render dashboard page.
Project Structure: Final project directory structure will look like this.
Step 1: Create empty npm project folder and name it Project.
npm init -y
Step 2: Install require dependency.
npm i express ejs body-parser
Step 3: Client files, the default behavior of EJS is that it looks into the ‘views’ folder for the templates to render. So, let’s make a ‘views’ folder in our main node project folder and make two files named “login.ejs” and “dashboard.ejs” .
login.js is responsible for user login request and if login success user will redirect to dashboard.ejs.
Step 4: Create a file name server.js on your root folder. This file is has some middleware and it response on user request. Generally user login information is fetched from database but for our case it is fair to fetch it from a damy database.
Here, login handler route is redirect to ‘/dashboaard/[ USER EMAIL ]’ if user data matched else response with HTTP Client Error Code 401.
Please Login to comment...