Hướng dẫn nodejs session variables
In this article, we’ll learn about how to use session variables with Node.js. Session Management in Node.js:
Cookies in session management :
Let us take a few examples to understand this concept better :
Example 1: View counter for the client. When a user visits the site. Then a cookie is assigned to the user and a session is created. The next time when a user visits, he is recognized by the cookie, and the variable gets updated. The steps required for “View Count” are given below: Step 1: Initialize the project using the following command in terminal npm init Step 2: Install the following required modules using the terminal. npm install express express-session cookie-parser Step 3: Create an app.js file as given below. Project Structure Image: Your project Structure should look like this: Step 4: Write down the following code in the app.js file. Javascript
Step 4: Run the file using the below command in the terminal. node app.js Output: The number of times you visit the same page, the number of times counter will increase. Example 2: Suppose there are three links login, logout, and profile. The user can’t go to the profile directly until he logged in. When the user logs in the session are created and the session will be destroyed after logout. Approach: We are creating a login logout page. Whenever a user logs in we put that user into the session and throughout the session, user would stay in that session. When the user logs out, we will destroy the session. The steps required for the “Login Logout Page” are given below: Step 1: Initialize the project and create a package.json file. npm init Step 2: Install the following required modules for the project. npm i express express-session cookie-parser Step 3: Create an app.js file as shown below Project Structure image: Your project Structure should look like this: Step 4: Write down the following code in a given file. Javascript
Step 5: Run the file using the following command in the terminal. node app.js Output: |