(License: CC BY-SA 4.0)
npm
)node --version
npm --version
mkdir hello-world
cd hello-world
pwd
package.json
file with the following command:
npm init -y
-y
)npm install --save express
node_modules
folder --save
option will make an entry inside the package.json
file)npm install -g nodemon
nodemon
utility system-wide sudo
powers)index.js
(use any text editor):
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send("Hello world!");
});
app.listen(3000);
'/'
) of your website and print.nodemod index.js
Hello World
api.js
file with the contents:
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var multer = require('multer');
var upload = multer();
var app = express();
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
//Require the Router we defined in movies.js
var movies = require('./movies.js');
//Use the Router on the sub route /movies
app.use('/movies', movies);
app.listen(3000);
node install --save body-parser
node install --save cookie-parser
node install --save multer
movies.js
is loaded, which we will create in the next step.app.use()
an ExpressJS Router is set up for the /movies
sub-URLsmovies.js
:
var express = require('express');
var router = express.Router();
var movies = [
{id: 101, name: "Fight Club", year: 1999, rating: 8.1},
{id: 102, name: "Inception", year: 2010, rating: 8.7},
{id: 103, name: "The Dark Knight", year: 2008, rating: 9},
{id: 104, name: "12 Angry Men", year: 1957, rating: 8.9}
];
//Routes will go here
module.exports = router;
router.get('/', function(req, res){
res.json(movies);
});
/
, which now points under /movies
where the Router is attached in api.js
.nodemon api.js
[{"id":101,"name":"Fight Club","year":1999,"rating":8.1},
{"id":102,"name":"Inception","year":2010,"rating":8.7},
{"id":103,"name":"The Dark Knight","year":2008,"rating":9},
{"id":104,"name":"12 Angry Men","year":1957,"rating":8.9}]