Wednesday, February 7, 2018

Build a Node JS API

To do this API practice I used Express as framework of Node JS, MongoDB as the database, and a package called body-parser to help deal with JSON requests.

You have to create a new folder and cd into it...
Then you have to run
npm init

After that you can see package.json file.

To use Express as framework for Node JS we have to install Express by typing
npm install --save express mongodb@2.2.16 body-parser

Then installing Nodemon as a dev dependency is a best way. Because it’s a simple little package that automatically restarts the server when files change.

npm install --save-dev nodemon

Then we have to add the following in package.json

"scripts": {
"dev": "nodemon server.js"
},

Therefore, the final package.json file will be like this

{
"name": "notable",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.14.0",
"mongodb": "^2.2.16"
},
"devDependencies": {
"nodemon": "^1.11.0"
}
}

Then server.js file should be created. This file is main to run an app.

So, inside the server we have to require our dependency packages ..
Here..

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();

MongoClient will interact with database.
Then we have to initialize the app as an instance of Express,  framework.

Afterward we have to define the port number to listen for HTTP requests.

const port = 8000;
app.listen(port, () => {
console.log('We are live on ' + port);
});


Then we have to go to terminal and type  
npm run dev 

Yeah.. we launched our server.. now you can see on localhost:8000 on your browser..

REad more... 

No comments:

Post a Comment