Let’s create a simple Node.js backend and make a GET request.
First, you will need npm installed on your computer. Go to the node website and download node.js onto your computer. You are now able to run npm commands. You will also need a text editor. You can download my favorite, Visual Studio Code, here.
Now, go ahead and create a new folder in your terminal. Inside the new folder run: npm init -y to create a Node.js project, and then create a index.js file.
We are also going to use Express, which is a web framework for Node.js. To install Express, run: npm i express. Now you can use the shortcut code . to open the folder in VS Code. These commands are below.
Awesome! Next let’s make a start script in our package.json file. The package.json file holds varioius metadata relevant to the project. This metadata includes the name of the project, the dependencies, and the scripts. Let’s go ahead and create a start script to make it easier to start the server. After the test script write: “start”: “node index.js” (make sure to put a comma after the test script).
We’ll invoke the express variable and assign that to a variable called app.
Next we can declare a variable that will designate which localhost port the server will be using.
Once that initial setup is completed, we are now able to finally create our GET request. A GET request is a HTTP method that requests a representation of the specified resource. We can use the app variable we made and the Express routing method for GET, which is .get(), to create the GET request. The Express GET request methods takes in apath, which we’ll call ‘/fun’, and a callback function. For the purposes of this basic example, we’ll use the json method on the response to make a simple message appear at the ‘/fun’ route. All this amounts to the following:
All that’s left is to tell the app which port it is listening to.
And that’s all there is to it! So now if you run: npm start in the terminal (make sure you are still in the same folder!) and go to localhost:4000/fun in your browser, you should see the hello world message.