Open In App
Related Articles

Design first Application using Express

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Express is a lightweight web application framework for node.js used to build the back-end of web applications relatively fast and easily. Here we are going to write a simple web app that will display a message on the browser. 

Setup:

  • Install node: Follow the instruction given on this page if you have not installed the node.
  • Check whether node and npm are installed or not by typing the following two commands in the command prompt or terminal.
node --version
npm --version
  • Install Express: Go to this page to install Express. Don’t forget to make a working directory for the project as mentioned there.

Let’s get started:

  • Create a file ‘firstapp.js’ and write the code as shown below. 

javascript

const express = require('express');
app = express();
 
app.get('/', function (req, res) {
    res.type('text/plain');
    res.status(200);
    res.send('GeeksforGeeks');
});
 
app.listen(4000, function () {
    console.log('Listening.....');
});

                    

Start the app by typing the following command:

node filename.js

You will see something like this. 

 This means that the server is waiting for a request to come.

Open any browser of your choice and go to “localhost:4000/” and you will see the message “GeeksforGeeks”. 

Explanation:

const express = require('express');

require() is a node.js function used to load the external modules. Here ‘express’ is that external module.

app = express();

Here an object of an express module is created on which different methods will be applied like get, set, post, use, etc.

app.get('/', function(req, res){
    res.type('text/plain');
    res.status(200);
    res.send('GeeksforGeeks');
});

get() is a function by which we add a route and a function that will get invoked when any request will come. The function which we are passing to get(), sets attributes of the response header by updating the status code as 200, mime-type as ‘text/plain’, and finally sends the message ‘GeeksforGeeks’ to the browser.

app.listen(4000);

This is used to establish a server listening at port 4000 for any request.


Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads