RESTful Web Services with Express Framework and mongoose.
Slides do conjunto (32)
-
RESTful Webservices - Express Framework
- Web Applications
- Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
- APIs
- With a myriad of HTTP utility methods and middleware at your disposal, creating a robust API is quick and easy.
- Performance
- Express provides a thin layer of fundamental web application features, without obscuring Node.js features that you know and love.
- Hello world example (app.js):
- var express = require('express')
- var app = express()
- app.get('/', function (req, res) { res.send('Hello World!') })
- app.listen(3000, function () { console.log('Example app listening on port 3000!') })
- Run:
- $ node app.js
- http://expressjs.com/
-
- Routing refers to the definition of application end points (URIs) and how they respond to client requests.
- Route methods
- A route method is derived from one of the HTTP methods, and is attached to an instance of the express class.
- The following code is an example of routes that are defined for the GET and the POST methods to the root of the app.
- There is a special routing method, app.all(), which is not
- derived from any HTTP method. This method is used for loading middleware
- functions at a path for all request methods.
- // GET method route
- app.get('/', function (req, res) {
- res.send('GET request to the homepage')
- })
- // POST method route
- app.post('/', function (req, res) {
- res.send('POST request to the homepage')
- })
- --------------------------------------------------------------
- app.all('/secret', function (req, res, next) {
- console.log('Accessing the secret section ...')
- next() // pass control to the next handler
- })
-
- Route paths, in combination with a request method, define the
- endpoints at which requests can be made. Route paths can be strings,
- string patterns, or regular expressions.
- The characters ?, +, *, and () are subsets of their regular expression counterparts. The hyphen (-) and the dot (.) are interpreted literally by string-based paths.
- // It will match requests to the root route, /.
- app.get('/', function (req, res) { res.send('root') }) // It will match requests to /about.
- app.get('/about', function (req, res) {
- res.send('about') }) // It will match /abe and /abcde
- app.get('/ab(cd)?e', function (req, res) { res.send('ab(cd)?e') })
- Route parameters are named URL segments that are used to capture the
- values specified at their position in the URL. The captured values are
- populated in the req.params object, with the name of the route parameter specified in the path as their respective keys. Route path: /users/:userId/books/:bookId
- Request URL:
- http://localhost:3000/users/34/books/8989
- req.params: { "userId": "34", "bookId": "8989" } // Specify the route parameters ...
- app.get('/users/:userId/books/:bookId',
- function (req, res) { res.send(req.params) })
-
- You can provide multiple callback functions that behave like middleware to handle a request. The only exception is that these callbacks might invoke next('route')
- to bypass the remaining route callbacks. You can use this mechanism to
- impose pre-conditions on a route, then pass control to subsequent routes
- if there’s no reason to proceed with the current route.
- Route handlers can be in the form of a function, an array of
- functions, or combinations of both, as shown in the following examples.
- A single callback function can handle a route. For example:
- app.get('/example/a', function (req, res) {
- res.send('Hello from A!') })
- More than one callback function can handle a route (make sure you specify the next object). For example:
- app.get('/example/b',
- function (req, res, next) {
- console.log('the response will be sent
- by the next function ...')
- next() },
- function (req, res) {
- res.send('Hello from B!') }
- ) An array of callback functions can handle a route.
- A combination of independent functions and arrays of functions can handle a route. (http://expressjs.com/en/guide/routing.html)
-
- The methods on the response object (res) in the following
- table can send a response to the client, and terminate the
- request-response cycle. If none of these methods are called from a route
- handler, the client request will be left hanging.
- Method
- Descriptionres.download()Prompt a file to be downloaded.res.end()End the response process.res.json()Send a JSON response.res.jsonp()Send a JSON response with JSONP support.res.redirect()Redirect a request.res.render()Render a view template.res.send()Send a response of various types.res.sendFile()Send a file as an octet stream.res.sendStatus()Set the response status code and send its string representation as the response body.
- You can create chainable route handlers for a route path by using app.route().
- Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos.
- app.route('/book')
- .get(function (req, res) {
- res.send('Get a random book')
- })
- .post(function (req, res) {
- res.send('Add a book')
- })
- .put(function (req, res) {
- res.send('Update the book')
- })
-
- Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.
- The following example creates a router as a module, loads a
- middleware function in it, defines some routes, and mounts the router
- module on a path in the main app.
- Create a router file named birds.js in the app directory, with the following content:
- var express = require('express')
- var router = express.Router()
- // middleware that is specific to this router
- router.use(function timeLog (req, res, next) {
- console.log('Time: ', Date.now())
- next() })
- // define the home page route
- router.get('/', function (req, res) {
- res.send('Birds home page') })
- // define the about route
- router.get('/about', function (req, res) {
- res.send('About birds') })
- module.exports = router Then, load the router module in the app:
- var birds = require('./birds')
- // ...
- app.use('/birds', birds)
-
- Middleware functions are functions that have access to the request object (req), the response object (res),
- and the next middleware function in the application’s request-response
- cycle. The next middleware function is commonly denoted by a variable
- named next.
- Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware in the stack.
- If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.
- The following figure shows the elements of a middleware function call:
- http://expressjs.com/en/guide/writing-middleware.html
-
Express - Middleware - Example

- Legenda: Elements of a middleware function call.
- Here is an example of a simple “Hello World” Express application.
- var express = require('express')
- var app = express()
- app.get('/', function (req, res) {
- res.send('Hello World!') })
- app.listen(3000)
- The following code loads the myLogger middle-
- ware function before the route to the root path
- (/).
- var express = require('express')
- var app = express()
- var myLogger = function (req, res, next) {
- console.log('LOGGED')
- next() }
- app.use(myLogger)
- app.get('/', function (req, res) {
- res.send('Hello World!') })
- app.listen(3000)
-
I.RESTful webservice - Express framework
- 1. Open Eclipse Enide.
- 2. Select: File > New > Node.js Express Project.
- 3. Type Project Name and click finish.
- 4. Open app.js file and "Run As.." > Node Application.
- 5. Open firefox REST plugin and send GET method to http://127.0.0.1:3000

-

- Legenda: Run app.js as "Node Application"
-

- Legenda: Use RESTClient plugin in Mozilla Firefox to send GET request method.
-

- Legenda: Add /users route.
-
- Create a new node.js file:
- 1. File > New > helloRoute.js > Finish.
- 2. Type the following code.
- var express = require('express');
- var app = express();
- app.get('/hello',function(request, response) {
- response.send('Hello route');
- });
- app.listen(3000);
- 3. Run as Node application.
- 4. Test as:
- Method: GET
- URL: http://127.0.0.1:3000/hello

-
II. Express - Hello route - Test

- Legenda: Hello route.
-
III. Express - Hello route with parameter
- Create a new node.js file:
- 1. File > New > helloRouteParam.js > Finish.
- 2. Type the following code.
- var express = require('express');
- var app = express();
- app.get('/hello/:name',function(request, response) {
- response.send('Hello ' + request.params.name);
- });
- app.listen(3000);
- 3. Run as Node application.
- 4. Test as:
- Method: GET
- URL: http://127.0.0.1:3000/hello/Peter

- Legenda: Request by adding Peter as parameter.
-
IV. Express - Hello route with URL param.
- Create a new node.js file:
- 1. File > New > helloRouteUrlParam.js > Finish.
- 2. Type the following code.
- var express = require('express');
- var app = express();
- var url = require('url');
- app.get('/hello',function(request, response) {
- var get_params = url.parse(request.url, true).query;
- if (Object.keys(get_params).length == 0) {
- response.send('Hello everybody!'); }
- else {
- response.end('Hello ' + get_params.name); }
- });
- app.listen(3000);
- 3. Run as Node application.
- 4. Test as:
- Method: GET
- URL: http://127.0.0.1:3000/hello?name=Peter

- Legenda: Hello Peter using url parameter.
-
- Create new Express project, then edit app.js, copy and replace existing code by the following:
- var express = require('express')
- , routes = require('./routes')
- , http = require('http')
- , path = require('path')
- , contacts = require('./modules/contacts');
- var url = require('url');
- var app = express();
- app.set('port', process.env.PORT || 3000);
- app.use(express.favicon());
- app.use(express.logger('dev'));
- app.use(express.bodyParser());
- app.use(express.methodOverride());
- app.use(app.router);
- app.get('/contacts',function(request,response) {
- var get_params = url.parse(request.url, true).query;
- if (Object.keys(get_params).length === 0) {
- response.setHeader('content-type','application/jason');
- response.end(JSON.stringify(contacts.list()));
- } else {
- response.setHeader('content-type','application/jason');
- response.end(JSON.stringify(contacts.query_by_arg(get_params.arg, get_params.value))); }
- });
- http.createServer(app).listen(app.get('port'), function(){
- console.log('Express server listening on port ' + app.get('port'));
- } );
-
- 1. Make new folder: data.
- 2. Inside data folder created in step 1, create new file: contacts.json, then paste the following code:
- {
- "firstname": "Jhon",
- "lastname": "White",
- "title": "Mr.",
- "company": "SuperMoon Inc.",
- "job title": "Developer",
- "primarycontactnumber": "+525534567890",
- "othercontactnumbers": ["+52771456789","+52557223456789"],
- "primaryemailaddress": "jhon.white@supermoon.com.mx",
- "emailaddresses": ["j.w@yahoo.com","jhonw@gmail.com"],
- "groups": ["Dev","friends"]
- }
- 4. Create new folder modules and add file contacts.js inside it.
- var fs = require('fs');
- function read_json_file()
- {
- var file = './data/contacts.json';
- return fs.readFileSync(file);
- }
- exports.list = function()
- {
- console.log('list>ok');
- return JSON.parse(read_json_file());
- };
- 5. Run app.js as node application.
- 6. Test with GET request as:
- http://127.0.0.1:3000/contacts
-

- Legenda: Add new folders and files to a new Express project.

- Legenda: Response.
-
VI.1 RESTful WS - Express and Moongose
- RESTful intregration with Express framework and Moongose (MongoDB support). To test route (/) , do the following:
- 1. Open Eclipse Enide and Create New Express Project.
- 2. Edit package.json and replace contents with the following code:
- {
- "name": "prjExpressMongo",
- "version": "0.0.1",
- "private": true,
- "scripts": {
- "start": "node app.js"
- },
- "dependencies": {
- "express": "3.2.6",
- "jade": "*",
- "mongoose": "latest",
- "body-parser": "latest"
- }
- }
- 3. Select package.json and Run As npm install.

- Legenda: Run npm install to download required modules.
-
VI.2 RESTful WS - Express and Moongose
- 5. Replace app.js code with:
- var express = require('express')
- , routes = require('./routes')
- , http = require('http')
- , path = require('path');
- var mongoose = require('mongoose'); //MongoDB support
- var app = express();
- // all environments
- app.set('port', process.env.PORT || 3000);
- app.use(express.favicon());
- app.use(express.logger('dev'));
- app.use(express.bodyParser());
- app.use(express.methodOverride());
- app.use(app.router);
- // development only
- if ('development' == app.get('env')) { app.use(express.errorHandler()); }
- app.get('/', routes.index); // Handle Route(File: routes/index.js)
- http.createServer(app).listen(app.get('port'), function(){
- console.log('Express server listening on port ' + app.get('port'));
- });
- 6. Replace code in routes/index.js with:
- exports.index = function(req, res) {
- res.send('Hello MonDB world with Express!'); };
- 7. Run app.js as nodejs application.
- 8.Test with RESTclient (firefox plugin).
- Method: GET
- URL: http://127.0.0.1:3000
- Response Body:
- Hello MonDB world with Express!
-
VI.3 RESTful WS - Express and Moongose
- 1. Make new folder: models.
- 2. Define a new model schema to handle data. Inside models folder, create new file: ismuser.js, then paste the following code:
- var mongoose = require('mongoose'),
- Schema = mongoose.Schema;
- var ismuserSchema = new Schema({
- name: { type: String },
- age: { type: Number },
- role: { type: String, enum:
- ['Administrator', 'Teacher', 'Student', 'Coordinator']} });
- // Export ismUser model to use later in ismusers.js file.
- module.exports = mongoose.model('ismUser', ismuserSchema);
- 3. Add connection to mongodb in app.js.
- var express = require('express') , routes = require('./routes')
- , http = require('http') , path = require('path');
- var mongoose = require('mongoose'); //MongoDB support
- var app = express();
- app.set('port', process.env.PORT || 3000);
- app.use(express.favicon());
- app.use(express.logger('dev'));
- app.use(express.bodyParser());
- app.use(express.methodOverride());
- app.use(app.router);
- if ('development' == app.get('env')) {
- app.use(express.errorHandler()); }
- app.get('/', routes.index);
- mongoose.connect('mongodb://localhost/ismusers', function(err, res) {
- if(err) { console.log('ERROR: connecting to Database. ' + err); }
- else { console.log('MongoDB connected!')}});
- http.createServer(app).listen(app.get('port'), function(){
- console.log('Express server listening on port ' + app.get('port'));
- });
- 4. Open a Linux console to run mongo server:
- $ mongod
- 5. Run app.js as nodejs application.
- 6. Check in Eclipse Console window, message:
- Express server listening on port 3000
- MongoDB connected!
-
VI.4 RESTful WS - Express and Moongose
- 3. Create new route to handle requests (GET, POST, PUT and DELETE). Create new File: ismusers.js inside routes folder and paste the following code:
- // Import model scheme defined in /models/ismuser.js file
- var ismUser = require('../models/ismuser');
- //GET - Return all ismusers in the DB
- // Export findAllsmUsers method to use in app.js
- exports.findAllismUsers = function(req, res){
- // Call find to get all data in DataBase.
- ismUser.find(
- function(err, ismusers) {
- if(err) { res.send(500, err.message); }
- // Type message in console.
- console.log('GET /ismusers');
- res.status(200).jsonp(ismusers);
- });
- };
-
VI.5 RESTful WS - Express and Moongose
- //POST - Insert a new ismuser in the DB
- exports.addIsmUser = function(req, res) {
- console.log('POST /ismusers');
- console.log(req.body);
- var ismuser = new ismUser({
- name: req.body.name,
- age: req.body.age,
- role: req.body.role
- });
- ismuser.save(function(err, ismuser) {
- if(err){ return res.status(500).send(err.message); }
- res.status(200).jsonp(ismuser);
- });
- };
- //GET - Return a ismuser with specified ID
- exports.findById = function(req, res) {
- ismUser.findById(req.params.id, function(err, ismuser) {
- if(err) { return res.status(500).send(err.message); }
- console.log('GET /ismuser/' + req.params.id);
- res.status(200).jsonp(ismuser);
- }); };
- //PUT - Update a register already exists
- exports.updateIsmUser = function(req, res) {
- ismUser.findById(req.params.id, function(err, ismuser) {
- ismuser.name = req.body.name;
- ismuser.age = req.body.age;
- ismuser.role = req.body.role;
- ismuser.save(function(err) {
- if(err) { return res.status(500).send(err.message); }
- res.status(200).jsonp(ismuser); });
- }); };
-
VI.6 RESTful WS - Express and Moongose
- //DELETE - Delete a ismuser with specified ID
- exports.deleteIsmUser = function(req, res) {
- ismUser.findById(req.params.id, function(err, ismuser) {
- ismuser.remove(function(err) {
- if(err) { return res.status(500).send(err.message); }
- res.status(200).send();
- }); }); }
- 4. Add routes to exported functions in app.js. Open app.js and replace contents with the following code:
- var express = require('express')
- , bodyParser = require('body-parser')
- , routes = require('./routes')
- , ismusers = require('./routes/ismusers')
- , http = require('http')
- , path = require('path');
- var mongoose = require('mongoose'); //MongoDB support
- var app = express();
- // all environments
- app.set('port', process.env.PORT || 3000);
- app.use(express.favicon());
- app.use(express.logger('dev'));
- // Import modules.
- app.use(bodyParser.urlencoded({ extended: false }));
- app.use(bodyParser.json());
- app.use(express.methodOverride());
- app.use(app.router);
- // Connect to DataBase
- mongoose.connect('mongodb://localhost/ismusers', function(err, res) {
- if(err) { console.log('ERROR: connecting to Database. ' + err); }
- else { console.log('MongoDB connected!'); }});
- // development only
- if ('development' == app.get('env')) {
- app.use(express.errorHandler()); }
-
VI.7 RESTful WS - Express and Moongose
- // Add root route. GET call: http://127.0.0.1:3000
- // index will handle request.
- app.get('/', routes.index);
- // Add /ismusers route. GET call: http://127.0.0.1:3000/ismusers
- // findAllsimUsers will handle request.
- app.get('/ismusers', ismusers.findAllismUsers);
- // Add /ismusers/:id route. POST call: http://127.0.0.1:3000/ismusers/:id
- // addIsmUser will handle request.
- app.post('/ismusers', ismusers.addIsmUser);
- // Add /ismusers/:id route. GET call: http://127.0.0.1:3000/ismusers/:id
- // findById will handle request.
- app.get('/ismusers/:id', ismusers.findById);
- // Add /ismusers/:id route. PUT call: http://127.0.0.1:3000/ismusers/:id
- // updateIsmUser will handle request.
- app.put('/ismusers/:id', ismusers.updateIsmUser);
- app.delete('/ismusers/:id', ismusers.deleteIsmUser);
- http.createServer(app).listen(app.get('port'), function(){
- console.log('Express server listening on port ' + app.get('port'));
- });
- Test the following scenarios:
- 4. Run as nodejs application.
- 5. Configure RESTclient plugin for Request Header: Content-Type, application/json
- 6. Add new ismuser.
- 7. List ismusers.
- 8. Search ismuser by id.
- 9. Update existing ismuser.
- 10. Delete existing ismuser.
-
VI.8 RESTful WS - Express and Moongose


- Legenda: Configure Headers > Custom header in Firefox RESTClient
- Legenda: Request Header: Content-Type, application/json
-
VI.9 RESTful WS - Express and Moongose
- Add new ismuser:
- URL: http://127.0.0.1:3000/ismusers
- Method: POST
- Request Header: Content-Type, application/json
- Body:
- {
- "name": "Peter Pan",
- "age": "15",
- "role": "Student"
- }
- Note _id filed assigned to the new ismuser register, this id field could be used later to update or delete the register.

- Legenda: Register added.
-
VI.10 RESTful WS - Express and Moongose
- List ismusers:
- URL: http://127.0.0.1:3000/ismusers
- Method: GET
- Request Header: Content-Type, application/json
- Body:

- Legenda: List added ismusers.
-
VI.11 RESTful WS - Express and Moongose
- Update ismusers:
- URL: http://127.0.0.1:3000/ismusers/582e7c738033002c686cfb35
- Method: PUT
- Request Header: Content-Type, application/json
- Body:
- {
- "name": "Peter Perez",
- "age": "35",
- "role": "Teacher"
- }

- Legenda: Updated user.
-
VI.12 RESTful WS - Express and Moongose
- Search ismuser by id:
- URL: http://127.0.0.1:3000/ismusers/<id>
- Method: GET
- Request Header: Content-Type, application/json
- Body:
- Note:Change <id> for existing id ismuser.

- Legenda: ismuser found.
-
VI.13 RESTful WS - Express and Moongose
- Delete ismuser by id:
- URL: http://127.0.0.1:3000/ismusers/<id>
- Method: DELETE
- Request Header: Content-Type, application/json
- Body:
- Note:Change <id> for existing id ismuser.

- Legenda: Deletedismuser.
Informações
- Descrição
- Webservice with RESTful, nodejs, mongoose and express framework.
- Criado por
- Angel Martínez Rodriguez
- Visualizações
- 236
- Tags
- Avaliação