[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 ...
随机推荐
- 【leetcode】155 - Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...
- “内部类” 大总结(Java)
(本文整理自很久以前收集的资料(我只是做了排版修改),作者小明,链接地址没有找到,总之感谢,小明) (后面也对"静态内部类"专门做了补充) 内部类的位置: 内部类可以作用在方法里以 ...
- [LeetCode] Missing Number (A New Questions Added Today)
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missin ...
- 关于面试mysql优化的几点纪要
1.减少查询次数 ,如何减少 ? 2. 表结构优化,如何优化 ? 3. 列选取原则 ? 4.建索引原则 ? 5.mysql语句优化 ? 6.增加mysql处理性能 ? 通过这几点, 再来说 ...
- wpf4 文字 模糊 不清晰 解决方法
在窗口或控件上设置字体属性就可以了,如下:<UserControl x:Class="..." xmlns="http://schemas. ...
- pybombs 安装
参考:https://github.com/gnuradio/pybombs 先装:pip 然后: pip install PyBOMBS 更新源: pybombs recipes add gr-re ...
- poj 3006 Dirichlet's Theorem on Arithmetic Progressions
题目大意:a和d是两个互质的数,则序列a,a+d,a+2d,a+3d,a+4d ...... a+nd 中有无穷多个素数,给出a和d,找出序列中的第n个素数 #include <cstdio&g ...
- 重复安装Lync导致发布拓扑失败
重复安装Lync会引起发布拓扑错误,主要原因就是Lync在域控服务器写了东西. 在出错日志中看到guid,查资料说到域控的CN=Trusted Services,CN=RTC Service,CN=S ...
- [转] 苹果所有常用证书,appID,Provisioning Profiles配置说明及制作图文
转自holydancer的CSDN专栏,原文地址:http://blog.csdn.net/holydancer/article/details/9219333 首先得描述一下各个证书的定位,作用,这 ...
- rhel5.5 Oracle10g安装记录
---恢复内容开始--- Rhel5.5 Oracle10g安装成功截图如下