Writing my First Lines in Express JS

So, in the previous days, I have enrolled in Harkirat’s 100xDevs 0–100. I have known Frontend but to explore, I took some base classes and coded by first HTTP Server.

So, writing code is one thing and making it accessible to people is one thing, Express helps us to do the second one. It helps us to create the server and make it accessible to everyone.

[NOTE: running on a local server, will only give it access to devices connected to your network]

So, what is ExpressJs?

The fast, unopinionated, minimalist web framework for Node.js.

It's not the only framework of NodeJs, nor is it the best, but it is one of the most widely and has a great community to learn and practise.

Can you code a bit and explain the same?

I have tried explaining it in comments and also things I got to know while coding.

//index.js
const express = require("express");

function calculateSum(n) {
    let ans = 0;
    for( let i = 1; i <= n; i++){
        ans = ans + i;
    }
    return ans;
}
//Express.js application that defines a simple route for handling HTTP GET requests

const app = express();
//we are creating an instance of express.
//app is used to define routes and configure for your web applications

app.get("/", function(req, res) {
    //the above line states the route for HTTP GET request to root path
    // first argument states the route
    // second argument states the function that will get executed when route reached
    const n = req.query.n;
    //extracts the parameter n from req
    // example = "/?n=10"
    const ans = calculateSum(n);
    //we are calling a function and storing the result in ans
    res.send(ans.toString());
    //we are sending the response

})

const port = 3000; // or any port you prefer
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

Those 4 lines of code do a lot behind the scenes.

First, we import the express package to the express value.

We instantiate an application by calling the express() method.

Once we have the application object, we tell it to listen for GET requests on the / path, using the get() method.

To start this local server, you must have installed node and express.

If the above steps are completed, start by writing the below command in the terminal.

node index.js

Then open localhost:3000 in your browser.

Thats all about today.

Thanks

Harsh Chandwani

(X.com- heyy_harshh)