[Express] Level 5: Route file
Using a Router Instance
Let's refactor app.js
to use a Router
object.
Create a new router object and assign it to the router
variable.
var router = express.Router();
When we are done, our router
will be mounted on the /cities
path. With this in mind, change app.route('/cities')
to use router
and map requests to the root path.
app.route('/cities')
.get(function (request, response) {
if(request.query.search){
response.json(citySearch(request.query.search));
}else{
response.json(cities);
}
}) //to router.route('/')
.get(function (request, response) {
if(request.query.search){
response.json(citySearch(request.query.search));
}else{
response.json(cities);
}
})
Likewise, let's move our '/cities/:name'
route to our router
. Remember to update the path.
app.route('/cities/:name')
.get(function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo){
response.json(cityInfo);
}else{
response.status(404).json("City not found");
}
}) .delete(function (request, response) {
if(cities[request.cityName]){
delete cities[request.cityName];
response.sendStatus(200);
}else{
response.sendStatus(404);
}
}); //to router.route('/:name')
.get(function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo){
response.json(cityInfo);
}else{
response.status(404).json("City not found");
}
}) .delete(function (request, response) {
if(cities[request.cityName]){
delete cities[request.cityName];
response.sendStatus(200);
}else{
response.sendStatus(404);
}
});
Our router
is now ready to be used by app
. Mount our new router
under the /cities
path.
app.use('/cities', router);
var express = require('express');
var app = express(); var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false }); // In memory store for the
// cities in our application
var cities = {
'Lotopia': 'Rough and mountainous',
'Caspiana': 'Sky-top island',
'Indigo': 'Vibrant and thriving',
'Paradise': 'Lush, green plantation',
'Flotilla': 'Bustling urban oasis'
}; app.param('name', function (request, response, next) {
request.cityName = parseCityName(request.params.name);
}); var router = express.Router();
app.use('/cities', router);
router.route('/')
.get(function (request, response) {
if(request.query.search){
response.json(citySearch(request.query.search));
}else{
response.json(cities);
}
}) .post(parseUrlencoded, function (request, response) {
if(request.body.description.length > 4){
var city = createCity(request.body.name, request.body.description);
response.status(201).json(city);
}else{
response.status(400).json('Invalid City');
}
}); router.route('/:name')
.get(function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo){
response.json(cityInfo);
}else{
response.status(404).json("City not found");
}
}) .delete(function (request, response) {
if(cities[request.cityName]){
delete cities[request.cityName];
response.sendStatus(200);
}else{
response.sendStatus(404);
}
}); // Searches for keyword in description
// and returns the city
function citySearch(keyword) {
var regexp = RegExp(keyword, 'i');
var result = cities.filter(function (city) {
return city.match(regexp);
}); return result;
} // Adds a new city to the
// in memory store
function createCity(name, description){
cities[name] = description;
return name;
} // Uppercase the city name.
function parseCityName(name){
var parsedName = name[0].toUpperCase() + name.slice(1).toLowerCase();
return parsedName;
} app.listen(3000);
All HTTP Verbs
What function would you call to match all HTTP verbs?
Answer:
app.all();
Using All
Let's use the app.all()
method to handle the name
parameter instead of app.param()
.
Add a call to all()
for our router's '/:name'
route. Pass a callback function that accepts request
, response
, and next
.
router.route('/:name')
.all(function(request, response, next){ })
Now let's take our logic from the callback function passed to app.param()
and move it to our all()
callback.
router.route('/:name')
.all(function(request, response, next){
request.cityName = parseCityName(request.params.name);
})
var express = require('express');
var app = express(); var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false }); // In memory store for the cities in our application
var cities = {
'Lotopia': 'Rough and mountainous',
'Caspiana': 'Sky-top island',
'Indigo': 'Vibrant and thriving',
'Paradise': 'Lush, green plantation',
'Flotilla': 'Bustling urban oasis'
}; // Searches for keyword in description and returns the city
function citySearch(keyword) {
var regexp = RegExp(keyword, 'i');
var result = cities.filter(function (city) {
return city.match(regexp);
}); return result;
} // Adds a new city to the in memory store
function createCity(name, description) {
cities[name] = description;
return name;
} // Uppercase the city name.
function parseCityName(name) {
var parsedName = name[0].toUpperCase() + name.slice(1).toLowerCase();
return parsedName;
} var router = express.Router(); router.route('/')
.get(function (request, response) {
if(request.query.search) {
response.json(citySearch(request.query.search));
} else {
response.json(cities);
}
}) .post(parseUrlencoded, function (request, response) {
if(request.body.description.length > 4) {
var city = createCity(request.body.name, request.body.description);
response.status(201).json(city);
} else {
response.status(400).json('Invalid City');
}
}); router.route('/:name')
.all(function(request, response, next){
request.cityName = parseCityName(request.params.name);
})
.get(function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo) {
response.json(cityInfo);
} else {
response.status(404).json("City not found");
}
}) .delete(function (request, response) {
if(cities[request.cityName]) {
delete cities[request.cityName];
response.sendStatus(200);
} else {
response.sendStatus(404);
}
}); app.use('/cities', router); app.listen(3000);
Creating a Router Module
Our single application file is growing too long. It's time we extract our routes to a separate Node module under the routes folder.
Move our router
and its supporting code from app.js
toroutes/cities.js
.
routes/cities.js
var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false }); // In memory store for the
// cities in our application
var cities = {
'Lotopia': 'Rough and mountainous',
'Caspiana': 'Sky-top island',
'Indigo': 'Vibrant and thriving',
'Paradise': 'Lush, green plantation',
'Flotilla': 'Bustling urban oasis'
}; var router = express.Router(); router.route('/')
.get(function (request, response) {
if(request.query.search){
response.json(citySearch(request.query.search));
}else{
response.json(cities);
}
}) .post(parseUrlencoded, function (request, response) {
if(request.body.description.length > 4){
var city = createCity(request.body.name, request.body.description);
response.status(201).json(city);
}else{
response.status(400).json('Invalid City');
}
}); router.route('/:name')
.all(function (request, response, next) {
request.cityName = parseCityName(request.params.name);
}) .get(function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo){
response.json(cityInfo);
}else{
response.status(404).json("City not found");
}
}) .delete(function (request, response) {
if(cities[request.cityName]){
delete cities[request.cityName];
response.sendStatus(200);
}else{
response.sendStatus(404);
}
}); // Searches for keyword in description
// and returns the city
function citySearch(keyword) {
var regexp = RegExp(keyword, 'i');
var result = cities.filter(function (city) {
return city.match(regexp);
}); return result;
} // Adds a new city to the
// in memory store
function createCity(name, description){
cities[name] = description;
return name;
} // Uppercase the city name.
function parseCityName(name){
var parsedName = name[0].toUpperCase() + name.slice(1).toLowerCase();
return parsedName;
}
export our router
object so other files can have access to it. Remember, Node - therefore Express - uses the CommonJS module specification.
module.exports = router;
Our cities routes module is now ready to be used from app.js. Require the new routes/cities module from app.js
and assign it to a variable calledrouter
;
app.js
var router = require('./routes/cities');
app.js
var express = require('express');
var app = express();
var router = require('./routes/cities'); app.use('/cities', router);
app.listen(3000);
routes/cities.js
var express = require('express');
var bodyParser = require('body-parser');
var parseUrlencoded = bodyParser.urlencoded({ extended: false }); // In memory store for the
// cities in our application
var cities = {
'Lotopia': 'Rough and mountainous',
'Caspiana': 'Sky-top island',
'Indigo': 'Vibrant and thriving',
'Paradise': 'Lush, green plantation',
'Flotilla': 'Bustling urban oasis'
}; var router = express.Router(); router.route('/')
.get(function (request, response) {
if(request.query.search){
response.json(citySearch(request.query.search));
}else{
response.json(cities);
}
}) .post(parseUrlencoded, function (request, response) {
if(request.body.description.length > 4){
var city = createCity(request.body.name, request.body.description);
response.status(201).json(city);
}else{
response.status(400).json('Invalid City');
}
}); router.route('/:name')
.all(function (request, response, next) {
request.cityName = parseCityName(request.params.name);
}) .get(function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo){
response.json(cityInfo);
}else{
response.status(404).json("City not found");
}
}) .delete(function (request, response) {
if(cities[request.cityName]){
delete cities[request.cityName];
response.sendStatus(200);
}else{
response.sendStatus(404);
}
}); // Searches for keyword in description
// and returns the city
function citySearch(keyword) {
var regexp = RegExp(keyword, 'i');
var result = cities.filter(function (city) {
return city.match(regexp);
}); return result;
} // Adds a new city to the
// in memory store
function createCity(name, description){
cities[name] = description;
return name;
} // Uppercase the city name.
function parseCityName(name){
var parsedName = name[0].toUpperCase() + name.slice(1).toLowerCase();
return parsedName;
} module.exports = router;
[Express] Level 5: Route file的更多相关文章
- [Express] Level 5: Route Instance -- refactor the code
Route Instance Let's rewrite our cities routes using a Route Instance. Create a new Route Instance f ...
- [Express] Level 2: Middleware -- 1
Mounting Middleware Given an application instance is set to the app variable, which of the following ...
- [Express] Level 4: Body-parser -- Delete
Response Body What would the response body be set to on a DELETE request to /cities/DoesNotExist ? H ...
- [Express] Level 4: Body-parser -- Post
Parser Setup Assume the body-parser middleware is installed. Now, let's use it in our Express applic ...
- [Express] Level 3: Massaging User Data
Flexible Routes Our current route only works when the city name argument matches exactly the propert ...
- [Express] Level 3: Reading from the URL
City Search We want to create an endpoint that we can use to filter cities. Follow the tasks below t ...
- [Express] Level 2: Middleware -- 2
Logging Middleware Help finish the following middleware code in the logger.js file: On the response ...
- [Express] Level 1: First Step
Installing Express Let's start building our new Express application by installing Express. Type the ...
- Express web框架 upload file
哈哈,敢开源,还是要有两把刷子的啊 今天,看看node.js 的web框架 Express的实际应用 //demo1 upload file <html><head><t ...
随机推荐
- HighChart 实现从后台取数据来实时更新柱状和折线组图
前段时间公司让弄图表,给我说有HighCharts这个js插件,于是上网上搜,由于本人是写后端的,对于JavaScript和jQuery不是很熟悉,虽然找到了模板,但是还是不明白,所以一点一点的改,但 ...
- java基础语法知识
1.用消息框显示加法计算结果 package plusdialog; import javax.swing.JOptionPane; // import class JOptionPane publ ...
- Eclipse中用Link方式安装Maven插件(转载)
标签: it 分类: 开发软件 1.工具下载: Eclipse4.2 jee版本(注意是Jee,不是标准版的eclipse) 下载地址:http://www.eclipse.org/downloads ...
- QS之vcom
-2008 | -2002 | -93 | -87 choose VHDL 2008, 2002, 1993, or 1987 -explicit resolve ambiguous overload ...
- android 源码 中修改系统字体大小
在源码\android\frameworks\base\core\java\android\content\res \Configuration.java下有读取DEFAULT_FONTSCALE的值 ...
- What are some good resources for learning about Artificial Neural Networks
http://stackoverflow.com/questions/478947/what-are-some-good-resources-for-learning-about-artificial ...
- 【转】log4j详解及简易搭建
原文链接:http://www.cnblogs.com/mailingfeng/archive/2011/07/28/2119937.html log4j是一个非常强大的log记录软件. 首先当然是得 ...
- V7承保 bug代码
v7 bug1
- ckeditor 升级到 4.5
原来的项目用的是4.0+asp.net 3.5的,一直不错,这两天升级一下ckeditor到最新版4.5.1,用的是chrome浏览器测试,发觉TextBox.Text获取不到数据,在页面用js写do ...
- 第四章TPLINK 703n 重要恢复方法,非TTL串口连接
途中有一次为了试图能够在703N上挂载普通usb(可用空间只有2M多点),卸载了不少系统软件,甚至把UCI给卸载了,导致系统起来后没有SSH服务,只有DNS服务,几乎变砖.百般无奈下,终于找到有高人提 ...