[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/ ...
随机推荐
- Java核心 --- 注解
Java核心——注解 注解是jdk5以后的新特性,Spring和Hibernate等框架提供了注解的配置方式使用, 本文参考了浪曦风中叶的注解讲解,主要讲解jdk内置注解的用法,注解的声明和定义,以及 ...
- Python 以指定概率获取元素
这是Python cookbook的示例 1 def random_pick(some_list,probabilities): 2 x=random.uniform(0,1) 3 cumulativ ...
- Ubuntu 创建开机自启动脚本的方法
http://askubuntu.com/questions/9382/how-can-i-configure-a-service-to-run-at-startuphttp://stackoverf ...
- openstack neutron 各节点网络配置
- linux中ctrl+z和ctrl+c的区别
ctrl+c和ctrl+z都是中断命令,但是他们的作用却不一样.ctrl+c是强制中断程序的执行,而ctrl+z的是将任务中断,但是此任务并没有结束,他仍然在进程中他只是维持挂起的状态,用户可以使用f ...
- Servlet 2.4 规范之第一篇:概览
写在前面的话: 本系列是对<Java Servlet Specification Version 2.4>的完全翻译,力争但不保证完美表达出英文原文的思想内涵.如有疏漏之处,还 ...
- 1001Sum Problem
Time Limit: 1000/500 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): ...
- POJ2155Matrix(二维线段树)
链接http://poj.org/problem?id=2155 题目操作就是说,每次操作可以是编辑某个矩形区域,这个区域的0改为1,1改为0,每次查询只查询某一个点的值是0还是1. 方法:二维线段树 ...
- sql with(lock) 与事务
sql select查询语句 表后面携带 with(nolock) 会获取到 在事务中已经执行 但还未完成提交的 记录 即使表被锁住也能查询到 当事务最终执行失败时 查询到的记录可能没有啦 不 ...
- Javascript(JS)对Cookie的读取、删除、写入操作帮助方法
var CookieUtils = { get: function (name) { var cookieName = encodeURIComponent(name) + '=', cookieSt ...