[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 for the '/cities'
URL path and assign it to thecitiesRoute
variable.
var citiesRoute = app.route('/cities');
Move the code from our previous app.get()
route to a new GET route on the citiesRoute
object.
// GET route for /cities
citiesRoute.get(function (request, response) {
if(request.query.search) {
response.json(citySearch(request.query.search));
} else {
response.json(cities);
}
});
Move app.post()
to citiesRoute
.
// POST route for /cities
citiesRoute.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');
}
});
Now, let's get rid of the citiesRoute
temporary variable and use chaining function calls.
app.route('/cities')
.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');
}
});
Finally, let's move the old routes for the '/cities/:name'
URL path to use the new Route Instance API.
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);
}
});
Before:
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 = {}; var citiesRoute; // GET route for /cities
app.get('/cities', function (request, response) {
if(request.query.search) {
response.json(citySearch(request.query.search));
} else {
response.json(cities);
}
}); // POST route for /cities
app.post('/cities', 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');
}
}); // GET route for /cities/:name
app.get('/cities/:name', function (request, response) {
var cityInfo = cities[request.cityName];
if(cityInfo) {
response.json(cityInfo);
} else {
response.status(404).json('City not found');
}
}); // DELETE route for /cities/:name
app.delete('/cities/:name', 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 result = null;
var search = RegExp(keyword, 'i');
for(var city in cities) {
if(search.test(cities[city])) {
return city;
}
}
} // Adds a new city to the in memory store
function createCity(name, description) {
cities[name] = description;
return name;
} app.listen(3000);
Now:
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 = {}; app.route('/cities')
.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');
}
}); 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);
}
}); // Searches for keyword in description and returns the city
function citySearch(keyword) {
var result = null;
var search = RegExp(keyword, 'i');
for(var city in cities) {
if(search.test(cities[city])) {
return city;
}
}
} // Adds a new city to the in memory store
function createCity(name, description) {
cities[name] = description;
return name;
} app.listen(3000);
[Express] Level 5: Route Instance -- refactor the code的更多相关文章
- [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 ...
- [MEAN Stack] First API -- 6. Using Express route instance
For server.js, we update the code by using route instance. By using this, we can remove some duplica ...
- [Express] Level 1: First Step
Installing Express Let's start building our new Express application by installing Express. Type the ...
- [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 ...
随机推荐
- 字节顺序重置及“#include <algorith.h>”相关的STL最重要的头文件提醒
这两天在写一个程序,需要将二进制文件中的数据以指定结构读入内存,说明文档中有提到大端序和小端序(Big Endian or Little Endian) 的概念,就找了一下字节顺序重置的算法,在一篇名 ...
- [python]Python操作MySQL
[安装] 安装MySQL 安装MySQL不用多说了,下载下来安装就是,没有特别需要注意的地方. 一个下载地址:点击打开链接 [样例] ? 1 2 3 4 5 6 7 8 9 10 11 12 13 1 ...
- 遵守GPL的开源软件能用于商用吗?
遵守GPL的开源软件能用于商用吗? 比较经典的开源协议有 GPL,BSD 等等. GPL 软件可以用于商业用途,甚至说,RMS 撰写 GPL 协议的目的就是为了让自己的 GPL 软件 emacs 可以 ...
- PHP强大的内置filter (一)
<?php #PHP内置的validate filter $input_data = True; $result = filter_var($input_data,FILTER_VALIDATE ...
- pybombs 安装
参考:https://github.com/gnuradio/pybombs 先装:pip 然后: pip install PyBOMBS 更新源: pybombs recipes add gr-re ...
- PySpark调用自定义jar包
在开发PySpark程序时通常会需要用到Java的对象,而PySpark本身也是建立在Java API之上,通过Py4j来创建JavaSparkContext. 这里有几点是需要注意的 1. Py4j ...
- 使用Powershell 添加,选择更改订阅
PS C:\WINDOWS\system32> Import-AzurePublishSettingsFile 'C:\Users\Ling\Desktop\Free-11-24-2014-cr ...
- Cocos2d-JS v3.0 alpha 导入 cocostudio的ui配置
1.在新项目的根文件夹下打开project.json文件,修改: "modules" : ["cocos2d", "extensions", ...
- Ubuntu下gdb远程调试--warning: Could not load vsyscall page because no executable was specified解决方案
1. 首先安装gdbserver apt-get install gdbserver 2. 编译-g 程序 gcc -g test_gdb.c -o test_gdb 源码如下: #include & ...
- MecAnim
[MecAnim] MecAnim是Unity 4.0推出的新的动画系统,新系统使用Animator组件来控制动画,老系统使用Animation组件来控制动画.此篇讲述MecAnim系统. What ...