building Web projects based on Nodejs+express4+mongodb+angularjsBased on Nodejs build Web server use EXPRESS4 Build RESTful service use MongoDB as database, Mongoose component connection MongoDB use Angularjs+bootstrap design UI interface to use Webstorm 10.0.4 Development
The first part: The service end constructs
1. Establish Node.js Express APP via Webstorm
File-> New Project-> node.js Express App,
location column fill in the project name, select Nodejs and NPM location,
options-> Template Select Ejs
Create a new folder under the project models save MongoDB related corresponding model.
Create the model file Movie.js in the models directory.
Create restful API support files under the routes directory Movies.js
The completed directory structure is as follows
-Project
--bin
---www--
models
---movie.js--
node_modules
---...
--Public
---...
--Routes
movies.js
app.js
Package.json
2. Add Mongoose support and other related components in Package.json
{
' name ': ' Project ',
' version ': ' 0.0.0 ',
' private ': true,
' scripts ': {
' start ': ' Node./bin/www '
},
"dependencies": {"
body-parser": "~1.13.2",
"Cookie-parser": "~1.3.5",
"Debug": "~2.2.0", "
Ejs": "~2.3.3", "
Express": "~4.13.1",
"Morgan": "~1.6.1",
"ErrorHandler": "~1.4.2",
" Serve-favicon ":" ~2.3.0 ","
Mongoose ":" ~4.2.5 ",
" Connect-mongo ":" Latest ",
" express-session ":" Latest "
},
" engines ": {
" node ":" >=0.10.0 "
}
}
3. Establishment of the movie model in Movie.js:
var mongoose = require (' Mongoose ');
var Schema = Mongoose. Schema;
Define an DB object
var movieschema = new Schema ({
title:string,
releaseyear:string,
director:s Tring,
genre:string
});
Bind module for accessing outside
module.exports = Mongoose.model (' Movie ', movieschema);
4. Establish a movie based restful API in Movies.js
Introducing the movie model and opening the router
var Movie = require ('.. /models/movie.js ');
var express = require (' Express ');
var router = Express. Router ();
Implementing some of the basic functionality APIs
var Movie = require ('..
/models/movie.js ');
Get all movies Exports.list = function (req, res) {Movie.find (function (err, movies) {if (err) {
return Res.send (ERR);
} res.json (Movies);
})
};
Create new movie exports.create = function (req, res) {var movie = new movie (req.body);
Movie.save (function (err) {if (err) {return res.send (err);
} res.send ({message: ' Add a Movie '});
});
}; Update a movie exports.update = function (req, res) {//movie.findbyid (Req.params.id, callback) Movie.findone ({
_id:req.params.id}, function (err, movie) {if (err) {return res.send (err);
For (prop in Req.body) {Movie[prop] = Req.body[prop];
} movie.save (function (err) {if (err) {return res.send (err);
} res.json ({message: "Update a Movie"});
});
});
}; Delete a moviE Exports.delete = function (req, res) {Movie.remove ({_id:req.params.id}, function (err, Movie) {if (err) {
return Res.send (ERR);
} res.json ({message: ' Delete a movie '});
}); };
Export the feature module so that other parts can use the module
Module.exports = router;
5. Enable RESTful service
Introducing Mongoose in App.js to establish a database connection
var mongoose = require (' Mongoose ');
Connect to MongoDB
var dbname = ' movie ';
var url = ' mongodb://localhost:27017/' + dbname;
var mongooptions = {
server: {
socketoptions: {
keepalive:1
}}}
;
Mongoose.connect (URL, mongooptions);
Mongoose.connection.on (' Error ', function (err) {
console.log (' Mongo error: ' + err);
}). On (' Open ', function () {
console.log (' Connection opened ');
});
Introducing router enabling RESTful services
var express = require (' Express ');
var app = Express ();
var movies = require ('./routes/movies ');
App.use ('/api ', movies);
Because HTTP traffic is based on JSON format, you need to specify the request data format and encoding
var bodyparser = require (' Body-parser ');
App.use (Bodyparser.json ());
App.use (bodyparser.urlencoded ({extended:false}));
Export module
Module.exports = app;
6. Open the server in Bin/www
var app = require ('.. /app ');
var http = require (' http ');
var port = normalizeport (Process.env.PORT | | ' 3000 ');
App.set (' Port ', port);
Create HTTP server
var server = http.createserver (app);
Server.listen (port);
Run bin/www (node bin/www) to run the server. Part II: Front-End construction
The front end uses Angularjs+bootstrap to build 1. Introduction of Bower
Install Nodejs first, and use NPM tools to introduce Bower.
Create the following directory structure in sequence under the project folder pubic
-Project
--...
--Public
---CSS
---images
---js
----controller
----Service---views
index.html
Add Bower dependencies, create a new. bowerrc file under the project root, and specify the Bower installation path
{
"directory": "/public/bower_components"
}
Add Bower.json file Specify dependencies:
{
"name": "Project", "
Version": "0.0.0",
"dependencies": {"
jquery": "~2.1.3",
"bootstrap ":" ~3.3.2 ","
angular ":" ~1.3.8 ",
" Font-awesome ":" ~4.2.0 ",
" Angular-ui-router ":" ~0.2.13 ",
" Angular-bootstrap ":" ~0.12.1 "
}
}
Run Bower install, install related JS plugin 2. Introduction of the Angularjs component
Create a Angularjs project component app by creating a new module.js under Public > JS
' Use strict ';
var app = Angular.module (' app ', [
' Ui.router ', '
ui.bootstrap '
]);
Create a service to save Windows session
Session.storage.js
(function (APP) {
' use strict ';
App.factory (' Sessionstorage ', function ($window) {
var store = $window. sessionstorage;
return {
save:function (key, value) {
value = Angular.tojson (value);
Store.setitem (key, value);
},
get:function (key) {
var value = Store.getitem (key);
if (value) {
value = Angular.fromjson (value);
}
return value;
},
delete:function (key) {
Store.removeitem (key);
}
}})
(Angular.module (' app '));
Create a new movie service for HTTP requests
Movie.service.js
(function (APP) {' Use strict ';
App.factory (' Movieservice ', function ($http, $q) {return {getallmovies:function () {
var url = "Http://localhost:3000/api/movie/all";
var deferred = $q. Defer ();
$http. Get (URL). Then (function success (respdata) {var movies = Respdata.data;
Deferred.resolve (Movies);
The function error (reason) {deferred.reject (reason);
}
);
return deferred.promise;
}, Updatemovie:function (movie, id) {var url = "http://localhost:3000/api/movie/" + ID;
var deferred = $q. Defer (); $http. Put (URL, movie). Then (function success (respdata) {var movies = Respdata
. data; Deferred.resolvE (Movies);
The function error (reason) {deferred.reject (reason);
}
);
return deferred.promise;
}
}
}); }) (Angular.module (' app '));
Set up two controller processing related data operations in the Controller directory
Main.controller.js
(function (APP) {
' use strict ';
App.controller (' Maincontroller ', function ($scope, $rootScope, $state, sessionstorage, movies) {
$rootScope. title = ' Express_demo2 ';
$scope. movies = movies;
$scope. Updatemovie = function (movie) {
sessionstorage.delete (' movie ');
$state. Go (' movie.update ', {Data:movie});};})
(Angular.module (' app '));
Movie.controller.js
(function (APP) {
' use strict ';
App.controller (' Moviecontroller ', function ($scope, $rootScope, $state, $stateParams, Movieservice, Sessionstorage) c2/> $scope. Movie = $stateParams. Data;
if (! $scope. Movie) {
$scope. Movie = Sessionstorage.get (' movie ');
} else {
sessionstorage.save (' movie ', $ Scope.movie);
}
$scope. Update = function () {
var promise = Movieservice.updatemovie ($scope. Movie, $scope. movie._id);
Promise.then (function (data) {
alert (' Update success! ');
Sessionstorage.delete (' movie ');
$state. Go (' Movie.main ');}
);
};
}
) (Angular.module (' app '));
Establish Uirouter specified route
(function (APP) {' Use strict ';
App.config (function ($stateProvider, $urlRouterProvider, $locationProvider) {$locationProvider. Html5mode (True);
$urlRouterProvider. Otherwise ('/movie '); $stateProvider. State (' movie ', {abstract: ' true ', Templateurl: '/views/menu.h Tml '}). State (' Movie.main ', {url: '/movie ', Controller: ' Maincon Troller ', Templateurl: '/views/main.html ', resolve: {' movies ': functi
On (movieservice) {return movieservice.getallmovies ();
}}). State (' movie.update ', {url: '/movie/update ',
Controller: ' Moviecontroller ', Templateurl: '/views/update.html ', params: {
Data:null}});
}); }) (Angular. Module (' app ');
Create CSS under CSS files
. margin-top-20 {
margin-top:20px
}
. Title-font {
font-size:large;
Font-style:italic;
Font-family:consolas;
Font-weight:bold;
}
Declare app location in index.html and import related JS and CSS files
<! DOCTYPE html>