Skip to content
Related Articles
Open in App
Not now

Related Articles

Design first Application using Express

Improve Article
Save Article
  • Last Updated : 28 Jun, 2019
Improve Article
Save Article

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

Setup:

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

Let’s get started:

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




    var 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 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:

  • var 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 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 function by which we add route and a function which 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 send the message ‘GeeksforGeeks’ to the browser.

  • app.listen(4000);
    

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!