[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 ...
随机推荐
- cocos2dx 内存管理的理解
关于引擎内存管理的细节,网上有大量的详解,这里概括一下: cocos2d-x 的世界是基于 CCObject 类构建的,所以内存管理的本质就是管理一个个 CCObject. //CCObject 内部 ...
- C语言实现strcpy
strcpy.h: #ifndef STRCPY_H #define STRCPY_H #include <stdio.h> char *cat_strcpy(char *dst, con ...
- Sunday算法(字符串查找、匹配)
字符串查找算法中,最著名的两个是KMP算法(Knuth-Morris-Pratt)和BM算法(Boyer-Moore).两个算法在最坏情况下均具有线性的查找时间.但是在实用上,KMP算法并不比最简单的 ...
- UDP模式与TCP模式的区别
1.TCP有连接状态,而UDP没有. 2.TCP应用层使用无需考虑包的大小及发送情况,而UDP需要. 3.TCP中IP包大小的决定者是Socket,而UDP为应用层.
- Error when running Swift3 in REPL
Traceback (most recent call last): File "", line 1, in NameError: name 'run_one_line' is n ...
- tableView 显示区域偏移
在SB拖了一个tableView , 在显示的时候显示区域和tableView的区域不一致, (UITableViewWrapperView 和 UITableView frame不一致) 在SB上看 ...
- Spark给我们带来了什么惊喜?
Spark的一站式解决方案有很多的优势,具体如下.(1)打造全栈多计算范式的高效数据流水线 Spark支持复杂查询. 在简单的“map”及“reduce”操作之外,Spark还支持SQL查询. ...
- Struts – Wildcards example
Struts wildcards can helps to reduce the repetition in your struts-config.xml file, as long as your ...
- mac多版本python安装 pymysql
系统里面安装了多个python的版本,有2.7和3.4等.默认的2.7版本,但我开发需要3.4版本的. 默认情况下,用pip安装PyMySQL $sudo pip install PyMySQL 安装 ...
- devexpress皮肤设置
DEV的皮肤管理控件:SkinController: TdxSkinController; 皮肤设置:SkinController.SkinName := appInfo.SkinName; TdxR ...