Introduction to using ExpressJS with MongooseJS and NodeJS - Part 1

First let's see what is this expressJS,

According to their website, it's a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Creation of APIs is easy and provides a thin layer of fundamental web application features, without obscuring Node.js features that you know and love.

 So without further delay let's start coding,
  • Start by creating a folder for this project.
  • Navigate to it and run this command to create package.json which helps you to manage your dependencies,
    • npm init

  •  Then install express on your project,
    • npm install express -save



  •  Now let's create a simple server using Express.First create server.js file inside the app directory.Inside the file type the following code,
  •   Here, we are using express in server.js by requiring it.Then we have created the server using listen method.
  • Now run the server using following command,
    • node server.js
  •  Navigate to localhost:3000 on your browser



  •  You will see that kind of message,but that's ok for now since we haven't implemented CRUD operations.
  • Now let's move into the how we can integrate CRUD operation using express.
  • Type the following in server.js,

  •  In Express, we handle a GET request with the get method: 
    • app.get(path, callback)
    • The first argument, path, is the path of the GET request. It’s anything that comes after your domain name.
    • When we’re visiting localhost:3000, our browsers are actually looking for localhost:3000/. The path argument in this case is /.
    • The second argument is a callback function that tells the server what to do when the path is matched. It takes in two arguments, a request object and a response object:
  • Now,restart the server and you can see the following output,
  • Let's change our app so that we serve index.html page back to instead.
  • To do that we can use "sendFile" mehtod.
  •  Write the following cod in server.js
  •  The create index.html file in our application directory and add the following code,
  •  Restarting the server will render you the following output.
 This is how Express handles a GET request (READ operation) in a nutshell. At this point, you probably have realized that you need to restart your server whenever you make a change to server.js. This is process is incredibly tedious, so we gonna take a quick detour and streamline it by using a package called nodeman in my next part of this tutorial series.

You can check out the entire code here

Comments

Popular posts from this blog

Introduction to NodeJS Coding - Part1

Introduction to using ExpressJS with MongooseJS and NodeJS - Part 2

Machine Sharing And Enterpise Resource Planning System - Java (S.L.I.I.T 2nd Year ITP Project)