Backend development part 2 [Express App]

Share

Read Previous: Backend development part 1 [Node.js Server]

In the last article, we created a basic node server, now we will set up an express with a node server. Also, we will set up a request handler in the express app.

After setting up a project folder, it’s time to install express js in your project folder.

TABLE OF CONTENT

Installing Express JS

Express js is available for developers just like any other javascript package. Without hiding the Node.js functionalities you already know, Express offers a thin layer of basic web application features. To install express in your project run the command: npm install express

installing express package

Creating Express App

In index.js File:

const express = require('express')
const app = express()


app.get('/', (req, res) => {
  res.send('App running...')
})

app.listen(3000, () => {
  console.log(`+ Express App Started\n+ Port:${3000}`)
})

Understanding the above code: you first fetched the express package and in the 2nd line, we call the express function which is imported from the express package. It returns a layer of the basic web application.

Then, using get('path',callback()) we defined a route for the path / which will send a response with a text App running...

Next, we call the listen(port,callback()) function. Here, we assign a port to listen to HTTP requests and responses.

Now, it is time to start a server. to do so run the command npm run test

Running express app on port 3000

Testing express app

Now, we will open our application in the browser. Open http://localhost:3000 or http://127.0.0.1 in your browser.

Running express app in browser

Adding Routes in the express app

To add routes in the express app. we use app.get('/path',callback()) method. We will add 2 more routes /get-name and /get-random-number.

const express = require('express')
const app = express()


app.get('/', (req, res) => {
  res.send('App running...')
})


app.get('/get-name', (req, res) => {
  const name = "CodeWithSudeep";
  res.send(name)
})

app.get('/get-random-number', (req, res) => {
  const number = (Math.random() * 1000).toString();
  res.send(number)
})

app.listen(3000, () => {
  console.log(`+ Express App Started\n+ Port:${3000}`)
})

Now restart the server. To stop the current running thread by pressing ctrl+c and run the command: npm run test. Then, enter URL http://localhost:3000/get-name in the browser

/get-name path

Also, for route http://localhost:3000/get-random-number do the same.

/get-random-number path

We have successfully created the express app with 3 routes ( GET Request). In the next article, we will learn more about routing.

Other JS Article: Javascript

Share
Sudeep Mishra

Sudeep Mishra

Healing

%d bloggers like this: