[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/ ...
随机推荐
- 【LeetCode】104 - Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the long ...
- 帮哥们做的一个整理文档的小工具(C++ string的标准函数还是很给力的,代码在最下)
其实把程序用到生活中,真的能节约不少时间!程序的力量是无穷滴! 哥们的毕业设计是要做法律文书匹配之类的东东,有一步是要抽取所有的法律法规名称,而刚好我们要处理的文件中,法规的名称之前都有个‘.‘,所以 ...
- 写好Hive 程序的五个提示
转自http://www.alidata.org/archives/622 使用Hive可以高效而又快速地编写复杂的MapReduce查询逻辑.但是某些情况下,因为不熟悉数据特性,或没有遵循Hive的 ...
- Linux-head,tail用法
linux ---tail命令 linux中tail命令---用于查看文件内容 最基本的是cat.more和less. 1. 如果你只想看文件的前5行,可以使用head命令,如: head -5 /e ...
- spark的环境安装
1.安装sbt 正常安装流程. 在cmd里运行的时候,要提前设置代理(如果上网有代理),set JAVA_OPTS=-Dhttp.proxySet=true -Dhttp.proxyHost=172. ...
- jq 弹出窗口
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- 原生JS默认设置默认值的写法
json=json||{};json.type=json.type||'get';json.data=json.data||{};json.time=json.time||2000;
- jxse2.6在jdk8下,JxtaMulticastSocket存在的问题
JxtaMulticastSocket覆写了java.net.MulticastSocket的bind方法: @Override public void bind(SocketAddress addr ...
- HDU 5869 Different GCD Subarray Query (GCD种类预处理+树状数组维护)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5869 问你l~r之间的连续序列的gcd种类. 首先固定右端点,预处理gcd不同尽量靠右的位置(此时gc ...
- HDU1007最近点对(分治)
http://acm.hdu.edu.cn/showproblem.php?pid=1007 直接见代码吧.不过这个是N*logN*logN的 尽管如此,我怎么感觉我的比他们的还快??? #inclu ...