In this article i’ll talk about how to set up a NodeJS Express server application. At the end It should get across what NodeJS is, how to set up Express, and how to use GET requests using NodeJS.
Also this article is part of a series where i describe how to use GET requests, POST requests, and serve static files.
As I explained earlier NodeJS has a package manager built around it called NPM. And NPM can be used to download millions of modules that you can import into your project. One of these modules is called Express. Express is mostly used handle files when an HTTP request is received. Express can also do many other things, but we’ll stick to a simple GET request for now.
Whats an html file you ask? An html file is the building block to all website (some people call this a skeleton of the web) and a browser knows how to interpret an HTML file in a way that makes it work with other files. HTML has become very powerful over the last few years, going from just simple text to now being able to download files, lazy-load recourse's, make get requests to other files, and much much more (ill probably make a html article soon also).
Open up your command line after making sure that NPM has been successfully installed (NPM is the package manger for NodeJS and we’ll need it to download express). To make sure express is installed on your machine use npm -v And your terminal output should look something like this.
You should receive the version of NPM installed on your machine. After confirming that express is on your machine use this terminal command in the directory (directory also called folder) that your index.html file sits in.
Lets say that we have an html file that’s sitting in our current directory like this.
And we want Express to handle a GET request to a certain route in our URL and return our index.html file to the client that made that request. With Express this is made pretty simple. All you have to do is create a server.js (commonly called app.js) file, import the Express module, then initialize that class to an object variable. Then specify our variables listening point using the .listen(port, callback) method. All in all the code should look something like this.
Now save the data to the server.js file and run node followed by the server.js file name. It should look like this.
You receive our console output from the file. Then we’ll navigate to our web browser. And type localhost:8080. It should look like this.
Thanks for reading. I hope you found this article enjoyable and learned something in the process. If there’s something that you feel like I've left out then comment down below, or message me directly. Also leave a follow if you found this article informative! :)