Open In App

Design first Application using Express

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:



node --version
npm --version

Let’s get started:




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.

Article Tags :