An insight to get/post requests in Nodejs !

Article also published in Hashnode & Dev.to.

It was a few months back when I had picked up the basics of web development by learning HTML, CSS & Javascript and got acquainted with libraries like Bootstrap 4.0 and JQuery.

Now the next step was to move to the backend side of the web development. Since I had already learned javascript, I considered learning Nodejs with Express. In the initial phase of my learning, things flew above my head especially the get & post requests part. But for a comeback, I made a very simple calculator as my project. And it was a great learning experience this way. A quick guide to my simple project :

1.jpg

2.jpg

cd <your current directory>
npm init
npm install express body-parser

Now you are good to go!

4.jpg

3.jpg

After saving the js file, you must input the following in the terminal:

node server.js

This would start running the server on port 3000. You would see a note popping up in your terminal stating port created. In simple words, you have created a server that has an address of localhost:3000. Your browser would make a request on this port locally and then your local server would be made to respond to the query.

npm install -g nodemon

To run nodemon instead of node:

nodemon server.js

5.jpg

  1. The “/” symbol represents your home route. Recollect that in our HTML file we had put our action attribute in form tag equal to “/”.You may have different routes like “/about” or “/contact”. Suppose you create a “/about” route then to access the route you may have to search: localhost:3000/about

  2. Hence when you search, your browser makes a get request to your server at localhost & then your server renders the HTML file. Hence now you may be able to correlate why we were getting a Cannot GET / error.

  3. Now, when you give input and press the submit button you would get the Cannot POST/ error. This is because our have not set up the post response in our server.js.

6.jpg

7.jpg

With this, we have successfully created a basic backend server that can perform get/post requests. In simple words, GET is used to fetch information, and POST is used to push information.