For this tutorial you need to have:
- NodeJS installed on your machine. Other libraries will be installed with npm as we progress with the tutorial.
- IDE/ Editor of your choice (I’ll be using Bracket).
I’ll be working from a Windows machine, so I’ll be using the command line, but this can be done from any OS.
Let's start
Open the cmd (command line) and spin up a new NodeJS app (from the folder you want your app to be in) =>
mkdir consumer
cd consumer
npm init
your terminal/cmd will return some questions =>
name: consumer
Version:
Description: consume api
Entry point: server.js
test command:
git repository:
keywords:
author:
license: (ISC):
Is this okay? – yes
I left some fields blank. This way, it’ll use the default option. This should generate a folder in our consumer folder (package.json)
Next we will install express and nodemon
npm install express
npm install -g nodemon
express is a NodeJS framework, and nodemon will monitor our app, and restart the server if any change is made.
Head over to the consumer folder, and create server.js
/consumer/server.js =>
var express = require('express');
var index = require('./routes/index');
var port = 4200;
var app = express();
app.use('/', index);
app.listen(process.env.PORT || port, function()
console.log('Server started on port '+port)
});
In here, we setup our index.js file path to handle request and set our port to 4200.
Create a routes folder (in the consumer folder) and there, create an index.js file
/consumer/routes/index.js =>
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next){
res.send('The Beginning');
});
module.exports = router;
This is just a get request to return "The Beginning" to the browser.
[NB: All this setup is so we can view the json request on the browser. We can view it on the console, but I’m not so thrilled by that.]
Lets start the server. In your terminal/CMD =>
nodemon
Head over to a browser and type: http://localhost:4200
That's all for this tutorial.