Create Node.js web server with Express
In this article we will see and practice how to create a simple server with Node.js and handle any request from browser.
To use a website and have access to it, we need something can handle that request from the browser, which called Server. The web server will handle HTTP requests, for example Ruby on Rails Node.js with Express.js
Node.js is JavaScript runtime environment that executes JavaScript code outside a web browser. And has the ability to create web server to handle HTTP requests with using Framework called Express.js
Express.js
is a web application framework for Node.js, released as free and open-source software. It is designed for building web applications and APIs. It has been called the de facto standard server framework for Node.js.
Now we know what is Express.js let’s start building our simple server
First we have to install some dependencies for making our job easy from now on.
You can install a node dependency by running npm install dependency-name
. Rather than installing them one at a time, you can type npm install dependency1 dependecy2 dependency3
.
- express (the main framework)
- mongoose (to connect and interact with MongoDB)
- jsonwebtoken (to generate the tokens)
- bcryptjs (to hash password)
- validator (for database validations)
we will install more dependencies while our project gets bigger
run the commands
mkdir server
cd to this directory
touch server.js
to create file
npm init -yes
to initial new npm folder with defaults settings
npm install express mongoose jsonwebtoken bcryptjs validator
Creating the Server
We need to tell our app which port to run on. Keeping in mind that we will later be deploying our app to Heroku, which requires us to run our server on process.env.PORT
, add the following line to server.js
file:
This creates a new Express server. Now, let’s setup a basic route so that we can render some information on our page. Add the following to your file:
Finally, let’s tell Express to start a socket and listen for connections on the path. Do so by adding the following line to your file:
This will also log a success message to the console when our server is running successfully.
Now open your terminal and run node server
. If you have followed the steps correctly you will see your success message: 'Server running on port 3001' in terminal. Open up localhost:3001
in Chrome or Postman and you should see the text 'Hello World'!
Next we will create Account with MongoDb and connect it with our server.