[Express] Level 3: Massaging User Data
Flexible Routes
Our current route only works when the city name argument matches exactly the properties in the cities object. This is a problem. We need a way to make our code more flexible.
Inside our route, call the parseCityName() function passing in the name parameter. Assign the return value to the new variable called cityName.
var cityName = parseCityName(request.params.name);
function parseCityName(name) {
var parsedName = name[0].toUpperCase() + name.slice(1).toLowerCase();
return parsedName;
}
Now, using the city name returned from the parseCityName() function, lookup the corresponding description using the cities object and store it in the correct variable that will make the rest of the function work as intended.
var cityName = parseCityName(request.params.name);
var cityInfo = cities[cityName];
var express = require('express');
var app = express();
var cities = {
'Lotopia': 'Rough and mountainous',
'Caspiana': 'Sky-top island',
'Indigo': 'Vibrant and thriving',
'Paradise': 'Lush, green plantation',
'Flotilla': 'Bustling urban oasis'
};
app.get('/cities/:name', function (request, response) {
var cityName = parseCityName(request.params.name);
var cityInfo = cities[cityName];
if(cityInfo) {
response.json(cityInfo);
} else {
response.status(404).json('City not found');
}
});
function parseCityName(name) {
var parsedName = name[0].toUpperCase() + name.slice(1).toLowerCase();
return parsedName;
}
app.listen(3000);
Dynamic Routes I
Which Express function maps placeholders to callback functions, and is commonly used for running pre-conditions on Dynamic Routes?
Answer:
app.param();
Dynamic Routes II
Whenever we use our name parameter we want to parse it a specific way. Let's clean up our existing code so that all routes with a name parameter get the same special handling.
Call app.param() to intercept requests that contain an argument called'name'. Remember app.param() takes a callback function as its second argument, which uses the same signature as a middleware.
var express = require('express');
var app = express();
app.param('name', function(request, response, next){
});
Inside the app.param() callback function, call the parseCityName() function with the submitted name parameter. Set the return value to a new property in the request object called cityName.
app.param('name', function(request, response, next){
request.cityName = parseCityName(request.params.name);
});
Finally, call a function that moves processing to the next function in the stack.
app.param('name', function(request, response, next){
request.cityName = parseCityName(request.params.name);
next();
});
var express = require('express');
var app = express();
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);
next();
});
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");
}
});
function parseCityName(name){
var parsedName = name[0].toUpperCase() + name.slice(1).toLowerCase();
return parsedName;
}
app.listen(3000);
Dynamic Routes III
The following code has a Dynamic Route that takes a year as an argument and returns the city created in that year. The problem with our current implementation is that it breaks when invalid data is sent on client requests. Let's add some basic validation.
Call a function that intercepts Dynamic Routes with the 'year' param.
app.param('year', function(request, response, next){
});
Inside of that function, use the isYearFormat() function to check whether the year parameter is in a valid format. If so, then move processing to the next function in the stack.
if(isYearFormat(request.params.year)){
next();
}
If the year parameter is not in a valid format, then respond with a 400 HTTP status code and a JSON message 'Invalid Format for Year'.
app.param('year', function(request, response, next){
if(isYearFormat(request.params.year)){
next();
}else{
response.status(400).json('Invalid Format for Year');
}
});
var express = require('express');
var app = express();
app.param('year', function(request, response, next){
if(isYearFormat(request.params.year)){
next();
}else{
response.status(400).json('Invalid Format for Year');
}
});
var citiesYear = {
5000: 'Lotopia',
5100: 'Caspiana',
5105: 'Indigo',
6000: 'Paradise',
7000: 'Flotilla'
};
function isYearFormat(value) {
var regexp = RegExp(/^d{4}$/);
return regexp.test(value);
}
app.get('/cities/year/:year', function(request, response) {
var year = request.params.year;
var city = citiesYear[year];
if(!city) {
response.status(404).json("No City found for given year");
} else {
response.json("In " + year + ", " + city + " is created.");
}
});
app.listen(3000);
Dynamic Routes IV
With the proper validations in place for the following code, what would the output be for a GET request to /cities/year/500?
Answer:

[Express] Level 3: Massaging User Data的更多相关文章
- [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 5: Route file
Using a Router Instance Let's refactor app.js to use a Router object. Create a new router object and ...
- [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 4: Body-parser -- Delete
Response Body What would the response body be set to on a DELETE request to /cities/DoesNotExist ? H ...
- [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 2: Middleware -- 1
Mounting Middleware Given an application instance is set to the app variable, which of the following ...
- [Express] Level 1: First Step
Installing Express Let's start building our new Express application by installing Express. Type the ...
- Monitoring and Tuning the Linux Networking Stack: Receiving Data
http://blog.packagecloud.io/eng/2016/06/22/monitoring-tuning-linux-networking-stack-receiving-data/ ...
随机推荐
- cocos2dx 内存管理
转载自 ocos2dx 内存管理 - 小花原创博客 - 博客频道 - CSDN.NET http://blog.csdn.net/ring0hx/article/details/7946397 coc ...
- ThinkPad X220i 刷白名单BIOS,改装第三方无线网卡
ThinkPad X220i自带的网卡是REALTEK RTL8188CE,这张卡在Mac下目前是无解的.国外网站有该卡liunx.unix内核的驱动,但还是没有高人编译出来. 不等了,这卡没戏.正好 ...
- 解决 Unable to load DLL 'OraOps9.dll': 找不到指定的模块。 (Exception from HRESULT: 0x8007007E)
这个问题网上的答案是把oracle的home文件夹权限变为完全控制,然而并没有好用,还有一种方法是在编写的程序的config文件加入 <runtime> <legacyCorrupt ...
- emWin(ucGui) Edit控件数值模式 ——符号编辑 worldsing
emWin(ucGui) Edit控件数值模式出现负数值编辑时,如果键盘按键全可以设置独立的"-","+"键,这样可以正常编辑正数和负数,但是要没有设置这两个键 ...
- lua学习:游戏中的Lua
lua作为一种脚本语言,可以快速地开发游戏的原型.提高游戏的开发效率. 在游戏中,lua可以用来完成下面这些工作: ●编辑游戏的用户界面 ●定义.存储和管理基础游戏数据 ●管理实时游戏事件 ●创建和维 ...
- zendstudio 出现failed to create the java machine转
是因为配置java虚拟机内存太小 打开zend for eclipse 10.5时报了个错: failed to create the java virtual machine google了一下,解 ...
- 将UIImage保存成JPG或PNG格式存储在本地
-(void)pngAndJpg:(UIImage*)image{ NSString *pngPath = [NSHomeDirectory() stringByAppendingPathCompon ...
- CCPC总结
[印象·南阳] 10月15日出发,威海—烟台—郑州—南阳,一路上欢声笑语,从谁是卧底到各类纸牌游戏,也是欢乐.在从郑州到南阳的车上,对面的好像是河南当地的学长,感叹道工作不易的样子,说还是学生时代最为 ...
- hdoj 1404 Digital Deletions(博弈论)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1404 一看就是博弈论的题目,但并没有什么思路,看了题解,才明白 就是求六位数的SG函数,暴力一遍,打表 ...
- 联想硬盘分区表格式修改 GPT -> MBR
知识点分析:随机预装Win8的电脑,磁盘为GPT格式的,如果需要安装Win7等早期版本系统,需要转换为MBR格式的,使用Diskpart命令即可完成转换. 操作步骤: 注意:转换磁盘格式需要清空磁盘中 ...