Fundamentals of nodeJS
Getting started with ExpressJS
Express JS is a free open source web application framework for node JS. It simplifies node JS code with simple one or two lines of codes. Express is completely built on node JS.
Generate package.json
Lets install the express framework in our application. Firstly lets generate our package.json
file by running the command: npm init.
We get a bunch of questions, answer accordingly. The package.json
file after configurationππΌ
To install express run the command: npm i express
. We are installing the express as a regular dependency for our application. After the installation, a folder named node_modules
will be automatically added to the project. This folder contains all the dependencies of our application.ππΌ
Import package
Lets create a new file, app.js
which we will use as our entry point. Keep in mind that the express framework is a third party package so we have to import it using the require()
method and assigned it to a variable. The express package is a function. Lets create a variable app
and assign the value of the express object. ππΌ
Create a server
To create a server using express we use the listen() method. i.e app.listen()
.
The listen()
method receives 2 parameters. The first is the port number while the second is a callback function. The callback function will be executed as soon as the server starts. ππΌ
Lets see the output on the console. run: node app.js
ππΌ
Handling routes and sending response
The route consists of the http method and the url.
Handling get requests
Using the get()
method we can handle requests on the url. The first parameter of the get()
method is the root url. We pass a callback function as the second parameter which will be called whenever we make a get request on the url. The callback function receives 2 important parameters, request and response written as req and res . To send a response we use the send()
method.ππΌ
Lets see the response on the web browser. ππΌ
Using method chaining we can also set the status of the response ππΌ
Keep in mind that when we use the send()
method, by default the content type is text/HTML
. To send some json response we cannot use the send() method because with json response the content type is application/json
.So to achieve this we use the json()
method instead of the send method. ππΌ
Browser response ππΌ
That's all for this lesson.
Next: Frontend vs Backend development.
See you soonππ«‘βπΌ...