[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/ ...
随机推荐
- ajax 访问--提高安全性
首先受到struts token的启发,产生了客户端发起的ajax请求进行验证的想法,大致思路是客户端每次请求产生一个key ,然后服务端接收到key,然后解析,判断是否为合法key, 对于不带key ...
- Sublime Text 3快捷键
Ctrl+Shift+P:打开命令面板 Ctrl+P:搜索项目中的文件 Ctrl+G:跳转到第几行 Ctrl+W:关闭当前打开文件 Ctrl+Shift+W:关闭所有打开文件 Ctrl+Shift+V ...
- 转 毛笔字教程ps
跟大家分享一下毛笔字怎么做出来的,主要通过字体和素材叠加,十分简单,喜欢的一起练习.做完记得交作业. 先看看最终效果: 在网上是不是经常看这些碉堡了的毛笔感觉是不是很羡慕啊,现在我就教大家怎么做出这样 ...
- 数据库 CHECKDB 发现了x个分配错误和 x 个一致性错误
--1.在SQL查询分析器中执行以下语句:(注以下所用的POS为数据库名称,请用户手工改为自己的数据库名) use pos dbcc checkdb --2.查看查询结果,有很多红色字体显示,最后结果 ...
- C#完整的通信代码(点对点,点对多,同步,异步,UDP,TCP)
C# code namespace UDPServer { class Program { static void Main(string[] args) { int recv; byte[] dat ...
- sql的union用法
sql中union是很常见的,尤其是创建视图时,完全离不开union. SQL UNION 操作符合并两个或多个 SELECT 语句的结果,UNION 内部的每个 SELECT 语句必须拥有相同数量的 ...
- python报错ordinal not in range(128)
python编码问题:'ascii' codec can't decode byte 0xb0 in position 1: ordinal not in range(128) 这种问题有三种原因: ...
- easyui问题小记
在easyui1.4.3版本中,(其他版本不知道是不是也是这样的),绑定在datagridview上面的数据最好不要是带有特殊符号的字段,不然会导致部分的属性不好用,比如这样的字段 START_DA ...
- Android PHP 通过JSON进行数据交互
一.首先是Android客户端解析PHP返回的JSON数据 1.PHP代码(这里用到了数据库,如果没有准备数据库的话,可以自定义字符串) <?php $link=mysql_connect(SA ...
- C#取得当前目录 转载
/获取包含清单的已加载文件的路径或 UNC 位置. public static string sApplicationPath = Assembly.GetExecutingAssem ...