首页 > 代码库 > [MEAN] 6. Using Express route instance

[MEAN] 6. Using Express route instance

For server.js, we update the code by using route instance. By using this, we can remove some duplicate code.

For example:

app.get(‘/people‘, function(request, response){});app.post(‘/people‘, parseUrlencoded, function(request, response){});app.get(‘/people/:name‘, function(request, response){});app.delete(‘/people/:name‘, function(request, response){});

There are a lot of ‘/people/‘...

Using route instance:


app.route(‘/people‘)    .get(function(req ,res){})    .post(parseUrlEncoded, function(req, res){});app.route(‘/people/:name‘)    .get(function(req, res){})    .delete(function(req, res){});

 

 

In our case:


 

before:

//server.js‘use strict‘;var express = require(‘express‘);var cors = require("cors");var app = express();app.use(cors());var people = require(‘./controller/people‘);app.get(‘/people‘, people.getAll);app.get(‘/people/:id‘, people.get);app.listen(3000);

after:

‘use strict‘;var express = require(‘express‘);var cors = require("cors");var app = express();app.use(cors());var people = require(‘./controller/people‘);app.route(‘/people‘)    .get(people.getAll);app.route(‘/people/:id‘)    .get(people.get);app.listen(3000);

 

[MEAN] 6. Using Express route instance