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的更多相关文章

  1. [Express] Level 4: Body-parser -- Post

    Parser Setup Assume the body-parser middleware is installed. Now, let's use it in our Express applic ...

  2. [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 ...

  3. [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 ...

  4. [Express] Level 4: Body-parser -- Delete

    Response Body What would the response body be set to on a DELETE request to /cities/DoesNotExist ? H ...

  5. [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 ...

  6. [Express] Level 2: Middleware -- 2

    Logging Middleware Help finish the following middleware code in the logger.js file: On the response  ...

  7. [Express] Level 2: Middleware -- 1

    Mounting Middleware Given an application instance is set to the app variable, which of the following ...

  8. [Express] Level 1: First Step

    Installing Express Let's start building our new Express application by installing Express. Type the ...

  9. Monitoring and Tuning the Linux Networking Stack: Receiving Data

    http://blog.packagecloud.io/eng/2016/06/22/monitoring-tuning-linux-networking-stack-receiving-data/ ...

随机推荐

  1. 50种方法优化SQL Server数据库查询

    查询速度慢的原因很多,常见如下几种: 1.没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷) 2.I/O吞吐量小,形成了瓶颈效应. 3.没有创建计算列导致查询不优化. 4.内存不足 ...

  2. phpcms学习总结

    文件目录结构 根目录 | – api 接口文件目录 | – caches 缓存文件目录 | – configs 系统配置文件目录 | – caches_* 系统缓存目录 | – phpcms phpc ...

  3. 有趣的库:pipe(类似linux | 管道)库

    pipe并不是Python内置的库,如果你安装了easy_install,直接可以安装它,否则你需要自己下载它:http://pypi.python.org/pypi/pipe 之所以要介绍这个库,是 ...

  4. 使用ReflectionTestUtils解决依赖注入

    概述   当使用junit来测试Spring的代码时,为了减少依赖,需要给对象的依赖,设置一个mock对象,但是由于Spring可以使用@Autoware类似的注解方式,对私有的成员进行赋值,此时无法 ...

  5. RVM 安装&卸载

    安装: curl -L https://get.rvm.io | bash -s stable --autolibs=enabled [--ruby] [--rails] [—trace] $ cur ...

  6. accordion data-options iconCls

    <div id="aa" class="easyui-accordion" style="width:500px;height:300px;&q ...

  7. centos安装postfixadmin

    postfixadmin的安装,跟普通网站安装没什么区别 配置好虚拟目录,然后在数据库中创建数据库postfix 修改config.inc.php文件,详细搜索谷歌 访问http://www.你的域名 ...

  8. Ubuntu安装Burg

    友情提示:本文只介绍了如何安装Burg,没有关于卸载Burg的相关说明.事实上,我后来直接新装了12.04,我没有卸载Burg的经验.考虑到Burg事关系统引导的大事,安装的话按本文来做应该没有问题, ...

  9. python 前向引用

    即函数调用在函数定义之前 可以这样 def bbb(): print('this is b') aaa() def aaa(): print('this is a') bbb() ---------& ...

  10. dbcp 是什么

    Many Apache projects support interaction with a relational database. Creating a new connection for e ...