Ayúdanos a dar forma a GoConqr. ¿Qué deberíamos añadir?

Diapositivas

RESTful Web Services with Express Framework and mongoose.

Angel Martínez Rodriguez Web Applications Design Unit I Inglés 5,0Valoración media 5,0 de 5 (1 valoración) 32 diapositivas

Diapositivas del conjunto (32)

  1. 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/
  2. Express - Routing

    • 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
    • })
  3. Express - Route paths

    • 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) })
  4. Express - Route handlers

    • 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)
  5. Express - Response methods

    • 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')
    • })
  6. Express - express.Router

    • 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)
  7. Express - Middleware

    • 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
  8. Express - Middleware - Example

    • Express - Middleware - Example
    • Pie de imagen: 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)
  9. 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
    • I.RESTful webservice - Express framework
  10. I. Express - Run As...

    • I. Express - Run As...
    • Pie de imagen: Run app.js as "Node Application"
  11. I. Express - Test Get Method

    • I. Express - Test Get Method
    • Pie de imagen: Use RESTClient plugin in Mozilla Firefox to send GET request method.
  12. I. Express - Using route

    • I. Express - Using route
    • Pie de imagen: Add /users route.
  13. II. Express - Hello 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
  14. II. Express - Hello route - Test

    • II. Express - Hello route - Test
    • Pie de imagen: Hello route.
  15. 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
    • III. Express - Hello route with parameter
    • Pie de imagen: Request by adding Peter as parameter.
  16. 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
    • IV. Express - Hello route with URL param.
    • Pie de imagen: Hello Peter using url parameter.
  17. V.1 Express - Add contacts

    • 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'));
    • } );
  18. V.2 Express - Add contacts

    • 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
  19. V.3 Express - Add contacts

    • V.3 Express - Add contacts
    • Pie de imagen: Add new folders and files to a new Express project.
    • V.3 Express - Add contacts
    • Pie de imagen: Response.
  20. 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.
    • VI.1 RESTful WS - Express and Moongose
    • Pie de imagen: Run npm install to download required modules.
  21. 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!
  22. 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!
  23. 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);
    • });
    • };
  24. 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); });
    • }); };
  25. 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()); }
  26. 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.
  27. VI.8 RESTful WS - Express and Moongose

    • VI.8 RESTful WS - Express and Moongose
    • VI.8 RESTful WS - Express and Moongose
    • Pie de imagen: Configure Headers > Custom header in Firefox RESTClient
    • Pie de imagen: Request Header: Content-Type, application/json
  28. 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.
    • VI.9 RESTful WS - Express and Moongose
    • Pie de imagen: Register added.
  29. 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:
    • VI.10 RESTful WS - Express and Moongose
    • Pie de imagen: List added ismusers.
  30. 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"
    • }
    • VI.11 RESTful WS - Express and Moongose
    • Pie de imagen: Updated user.
  31. 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.
    • VI.12 RESTful WS - Express and Moongose
    • Pie de imagen: ismuser found.
  32. 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.
    • VI.13 RESTful WS - Express and Moongose
    • Pie de imagen: Deletedismuser.

Información

Descripción
Webservice with RESTful, nodejs, mongoose and express framework.
Creado por
Angel Martínez Rodriguez · nov 2016
Actualizado
10 ene 2017
Visitas
236
Etiquetas
restrestfulwebservicemongodbmongooseexpressnodejsjason
Valoración
Valoración media 5,0 de 5 (1 valoración)

Escríbenos

¿Sobre qué es tu mensaje?

¿Qué deberíamos añadir?