[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/ ...
随机推荐
- 迭代的模块itertools
itertools模块提供的全部是处理迭代功能的函数,他们的返回值不是list,而是迭代对象,只有在for循环的时候才会真正去计算. 使用迭代器的好处是在循环的时候才去取值,而直接返回值为list的结 ...
- Eclipse安装插件的方式
Eclipse有两种安装插件的方式,分为在线安装和手动安装,因为受到网络环境限制,推荐采用手动安装的方式,下面我们先来了解一下Eclipse手动安装插件的步骤. Eclipse手动安装插件: 第一种: ...
- TopFreeTheme精选免费模板【20130827】
今天我们整理了一些关于WordPress, Joomla, Drupal, Magento, OpenCart的最新免费模板主题,绝大多数都是来自ThemeForest的响应式风格模板主题.题材多样化 ...
- Linux网卡启动报错(this device is not active)
重启网络服务 service network restart 报如下错误: shutting down interface eth0: error:device "eth0" ...
- js_sl 分享
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- netdata linux环境下的安装
据说netdata监控很个性化,采用的显示方式也很漂亮,就来尝试安装.百度搜索到的安装教程的斑斑是1.0.顺藤摸瓜去wiki看了看,已经更新为1.4了,果断走起: 下载地址::https://gith ...
- Android_UI_点击按钮切换背景效果实现
实现按钮按下和释放,按钮背景图片相应切换效果的方法这里介绍两种,一种是在代码里实现,另一种是在xml文件里实现 一.在xml文件里 首先现在layout的一个xml文件下定义Button如下所示: [ ...
- NSInvocation Basics
In this article I'm going to cover the basics and usages of NSInvocation. What is NSInvocation? Appl ...
- ucenter同步登陆机制
有个ucenter可以用来实现多个站点同时登陆同时退出,用户同步的功能. 首先站点都要引入一个uc_client这样一个客户端,以登陆为例,登陆时首先会调用一个外部函数,uc_client/clien ...
- vs2008 release下调试状态设置[转]
这是一个老生常谈的话题,但还是有时候会漏洞一些设置.总结一些,总共需要三个地方设置, 分别是1)c\c++-> General->Debug Information Format. 2) ...