Basic Express & Node Server
A few days back I was talking to a few friends who like me are beginners in coding. So I thought I would write a little article about how to setup a basic node and express server from scratch.
First of all we want to check if we have Node installed in by first opening a terminal window. In my case I like to use iTerm. but you can ofcourse run the same command on gitBash, command prompt and the likes of it.
In most cases you should get a similar response. If not all you have to do is go to the node website and install node. Link here
Check if you get the above response after the installation by running node -v
Now that we have that out of the way.
Creating the Express Server :-
- Lets start by creating a folder called expressServer ( you can call this whatever you want).
- Then we create a server.js file by executing “touch server.js”.
3. Then its time for us to initialise the node package manager by executing “npm init -y”. ( You could also run “npm init” and go through the steps or just add -y to execute all with the default value of yes).
Now that we have our package.json we can start installing the basic dependencies we would like to have. In the same directory as the package.json run the following command :
Now we have a package.json that looks like -
Now we need to change this file a bit.
Here we added -
“type”: “module” to like 5 and changed the start script on line 9 to “nodemon server.js”.
After we have that out of the way we will head to the server.js file and edit that.
Line 1: We are bringing in the express framework.
Line 3: We are initialising the express framework and saving it into a constant.
Line 5: We are saving the port of our server into a constant. The process.env.PORT
is going to check your environment variables to see if you already have a PORT
defined there if not it will use PORT 8080
. In our case is going to use PORT 8080
.
Line 7: We are defining the first express route. lets you define a route handler for GET requests to a given URL, in this case ‘/’ and second argument as the response given is what we define within the function.
(“Congratulations you just made your first server.”).
Line 11: We use the built-in listen
method and it expects at least one argument, which is port number that our is located. You can pass a callback function as a second argument to the listen
method, in this case our function is going to log to the console that server is running and show in which port is running on.
If we followed the steps right we should be able to run our first server.
run the following command -
npm start
Now that we have our server running it should be running on http://localhost:8080.
And by browsing to localhost:8080 in your browser you should see the following command.
Congratulations here you are running a very basic Express/Node Server.