Author Profile Altaf Shaikh
Altaf Shaikh

BE Engg | Python Dev | Content Writer | Founder of TeachMeBro | Blockchain Dev | Django

Todo App - Setting Up Express App

January 26th 2021   89

Todo App - Setting Up Express App
Todo App - Setting Up Express App

In this section, we will setup our Express server to handle HTTP request made by any client.

Now, open the terminal in your project folder to create a package.json file using below command, this file will store the basic info about our project and our project dependencies

npm init -y

-y flag will skip all the question asked by npm init command and directly create a package.json file you can also run npm init

so, once we have our package.json file we can now move on to installing some packages.

npm install express dotenv 

We had installed express to create a backend server and dotenv to load and read environment variables.

npm install -g nodemon

We are installing the nodemon package globally because nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected. So that we don't need to manually restart the server for any changes in the code.

Next, create a file called app.js and lets create an express application server which is running on PORT 3000 and also we will store this PORT value inside the .env file and read using dotenv package.

// .env file

PORT=3000

app.js

// import express 
const express = require("express");

// import dotenv
const dotenv = require("dotenv");

// load environment variable
dotenv.config({ path: ".env" });


// read env variable using process.env.<your_env_variable_name>
const PORT = process.env.PORT;


// initialize express app

const app = express();


// sending a hello response on visiting http://localhost:3000/
app.get("/", (req, res) => {

  res.status(200).json({ message: "Hi I am Server", data: "no data on this endpoint" });

});


// listening for any HTTP requests on PORT 3000
app.listen(PORT, () => {

  console.log(`Server is running at http://localhost:${PORT}`);

});

So our express app is Setup. Run the below command and open your browser and visit http://localhost:3000 to see response from server

nodemon app.js

Output:

{ message: "Hi I am Server", data: "no data on this endpoint" }


You should see similar output on your browser on visiting  http://localhost:3000