[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 ...
随机推荐
- anible包模块管理
ansible使用包管理模块 一般使用的包管理模块的RPM,和YUM 参数 必填 默认 选择 说明 Conf_file No YUM的配置文件 Disable_dbg_check No No Yes/ ...
- 【LeetCode】226 - Invert Binary Tree
Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Notice: Goog ...
- 前端面试题(JS篇)
原题地址:http://handyxuefeng.blog.163.com/blog/static/454521722013111714040259/ 好吧,最近打算换工作,所以关注比较多的是面试题, ...
- static public和 public static 区别
static:加static 的是静态成员,不能实例化在你运行的时候他自己在内存中开辟了块空间,不用在new, 有点像全局变量,如果不用你必须去 实例化(new)才能用 static是静态的意思,pu ...
- DzzOffice1.0 Beta2 全新安装图文教程及界面简单了解
本文说明:本文档用于帮助您全新安装完整的 DzzOffice Beta版软件.DzzOffice 是一款开源的云存储与应用管理工具,主要用于企业管理阿里云.亚马逊等云存储等空间,把空间可视化分配给成员 ...
- asp.net mvc 4 编译错误 CS0012
CS0012: The type 'System.Data.Objects.DataClasses.EntityObject' is defined in an assembly that is no ...
- 简单版问卷调查系统(Asp.Net+SqlServer2008)
1.系统主要涉及以下几个表 问卷项目表(Q_Naire) 问卷题目表(Q_Problem) 题目类型表(Q_ProblmeType) 题目选项表(Q_Options) 调查结果表(Q_Answer) ...
- jy
222 DROP TABLE t_vhl_jy_car; CREATE TABLE t_vhl_jy_car( VEHICLE_JY_CODE ) PRIMARY KEY, VEHICLE_CODE ...
- HDU 4499 Cannon (暴力求解)
题意:给定一个n*m个棋盘,放上一些棋子,问你最多能放几个炮(中国象棋中的炮). 析:其实很简单,因为棋盘才是5*5最大,那么直接暴力就行,可以看成一行,很水,时间很短,才62ms. 代码如下: #i ...
- NS_ENUM & NS_OPTIONS
When everything is an object, nothing is. So, there are a few ways you could parse that, but for the ...