Tuesday, November 6, 2018

How to setup a server with Nodejs and Expressjs (Deploy on Heroku)

What we'll do ? 

In this tutorial, we will be creating a simple "Hello-Node" web app server using NodeJs and ExpressJs. We will deploy this web app on Heroku!

What are Requirements?

Visit the links given above and install all in your system and Signup for a Heroku Free Account!

Note: I'm assuming that you've some knowledge of JavaScript.

Let's Start!

Working on Local Environment

  • Create a directory and enter in the same.
  • In the directory enter npm init
  • Install ExpressJs npm install --save express
  • Create a file server.js
  • In Server.js import Express
    const express = require('express')
    const app = express()
  • declare a port variable

    var port = process.env.PORT || 8080;

    Instead of forcing server to listen to a specific port may result in error or server crash!

    What's process.env.PORT ?
    In many environments (e.g. Heroku), and as a convention, you can set the environment variable PORT to tell your web server what port to listen on.
    So process.env.PORT || 8080 means: whatever is in the environment variable PORT, or 8080 if there's nothing there.
  • Now, Let's write something which will appear on website!

      
    
    app.get("/", function(req, res){
    
        res.send('Hello Node');
     
     });
     
  • Now We'll make this app listen to either port 8080 or whichever is configured as per this host (heroku here).
    app.listen(port, function(){
    console.log('App Running on port ' + port);
    })
  • Now, Test if it works on local environment! run:
    node server.js
  • Go to localhost:8080 to see if it's working!
  • Final server.js will look like -

    
    const express = require("express");
    const app = express();
    
    
    var port = process.env.PORT || 8080;
    
    
    app.get("/", function(req, res){
    res.send('Hello Node!');
    });
    
    
    app.listen(port, function(){
    console.log('App Running on port ' + port);
    })
    
    

 Deploying on Heroku

  • Run git init  in that directory.
  • Run heroku login in terminal or comand line! and Provide login information which you used to create account on heroku.
  • Run heroku create
    It'll clone your repo into heroku server.
  • Run git add . and git commit -m "initial commit" 
  • Finally Push your code on heroku cloud!
    git push heroku master
  • Now, Run heroku open
    It'll open the url in browser on which your web app is deployed
This was the simplest app deployed on cloud using NodeJs and ExpressJs.

If I missed anything or you've got stuck somewhere! Shoot your questions below.
Thanks for passing by :)
Share:

0 comments:

Post a Comment