This is the first part of the series. In this series, we will start with the basics of NodeJS and move towards building a Restful API with all the features like Authentication, Database integration and much more.
Now the first question comes in mind is Why Node ?
NodeJS is a runtime environment of JavaScript so the developers already familiar with JavaScript can easily learn and use NodeJS. Another benefit is Single threaded event loop that is responsible for abstracting I/O from external requests. There are many more reasons as well but these two are sufficient I think.
Now without wasting any time, we will directly jump to building an amazing restful API.
We will use express.js to build this API. If you have any queries regarding express go to their homepage and try to read the documentation.
As you are already familiar with JavaScript hello worlds. It will be the same for Node.
console.log('Hello World')
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hello World')
})
const port = process.env.PORT || 3000
app.listen(port, () => console.log(`App is listning on port ${port}`))
In the very first line of the above code, we imported the express module which returns a function that we stored in a variable called express. In the second line, we called express function which returns an object and we stored it in a variable called app. After that, we have written the code to handle GET request. This get method takes two arguments.
Now there are many different types of requests and we will talk about them in the upcoming posts.
In the last two lines, we are setting a port to listen to the requests. We passed the port number and an optional callback function (it will log a message to the console) in the listen method.
Now to check things working properly
Finally Congrats you have successfully created a web server that can respond to your get requests.
Happy learning.