Node.js +Express Tutorial for Web Dev-2021- Getting Started with web server using node.js and express
Node.js & Express is a popular combo used by a lot of applications worldwide. This tutorial helps you get started with Node.js and Express by building a simple web server.
All You need to start :
Create the Project
The first step in the tutorial is to create an empty folder & name it as you like . I am using Windows .
Open the Code editor and Press Ctrl + J to pen the terminal, and run this command: npm init -y
The above command creates the package.json file and initializes it with the default values. If you want to fill the fields manually, remove the -y flag and follow the instructions.
You have an initialized Node.js project, but there is no track of Express so far. So install it in your project. To add the latest stable version of Express, run the following command:
Now that Express is installed, your package.json file should look as follows:
You can see that Express was installed successfully because it’s listed under the “dependencies.” Now let’s move on to the next step — creating the server.
Create Express Server
Now open the index.js file, and start by writing the following lines:
What are these two lines doing?
- With the first line, you import Express into your project so you can use it. Each time you add a package to your project, you need to import it where you want to use it.
- In the second line, you call the Express function, which creates a new application and then assigns the result to the App constant.
Create routes and listen on a specific port
In the simplest terms, a route represents an endpoint which people can access. Write the following code in your file:
Let’s break this code into smaller pieces to under each line and function better:
- console.log(‘ ‘) — allows you to see the server is running or not.
- res.send( ) — As the user is currently requesting to access the home page, the server sends a respond as string.
You need to call the method listen to be able to start the server. Also, you can replace the port number (3333) with whatever number you want.
Full Source Code in Index.js file
Access the app in the browser
To start the application, run node index.js in the terminal. Remember index.js is the name I chose for this tutorial. However, you can name it app.js or whatever you want.
Now that the server is running, you can access it in your browser. Go to localhost:3000 and you should see the following message:
Congratulations !! Clap for yourself . We just build our very first Node.js Application using express.
Let me know in the comments if you like this tutorial and I’ll make more tutorial on Node.js and express.
Thank You !!