Design first Application using Express

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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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.....');
    });

    chevron_right

    
    

  • 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


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.