Day 17 of 100days of code.

Day 17 of 100days of code.

Β·

2 min read

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😊🫑✌🏼...

Β