City Search

We want to create an endpoint that we can use to filter cities. Follow the tasks below to to create this new route.

Create a new route for GET request to '/cities'. The second argument should be a callback function which takes request and response.

app.get('/cities', function(request , response){

});

From inside of our route, create an if statement that checks whether a value is set to the query string parameter search.

app.get('/cities', function(request , response){
if(request.query.search){ }
});

Inside of the if block, call the citySearch() function, passing in the user submitted parameter for search. Then return the result of the function as a JSON response.

app.get('/cities', function(request , response){
var keyword = request.query.search;
if(keyword){
response.json(citySearch(keyword));
}
});
var express = require('express');
var app = express(); var cities = ['Caspiana', 'Indigo', 'Paradise']; app.get('/cities', function(request , response){
var keyword = request.query.search;
if(keyword){
response.json(citySearch(keyword));
}
}); function citySearch (keyword) {
var regexp = RegExp(keyword, 'i');
var result = cities.filter(function (city) {
return city.match(regexp);
}); return result;
} app.listen(3000);

Dynamic Route Variables

Consider the following Dynamic Route:

app.get('/cities/:name', function (request, response) {
// ...
})

When requests come in for this route, how can we access the city name submitted by the user?

Answer:

requst.params.name

City Information

Now lets look up some information about the city.

Inside of our dynamic route, grab the name submitted by the user, lookup the city information on the cities object and assign it to the cityInfovariable.

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 cityInfo,
name;
name = request.params.name;
cityInfo = cities[name];
});

Check to see if cityInfo exists and if so, respond with the cityInfo in JSON format.

app.get('/cities/:name', function (request, response) {
var cityInfo,
name;
name = request.params.name;
cityInfo = cities[name]; if(cityInfo){
response.json(cityInfo);
}
});

If cityInfo does not exist, respond with a 404 HTTP status code and a JSON message that says "City not found".

app.get('/cities/:name', function (request, response) {
var cityInfo,
name;
name = request.params.name;
cityInfo = cities[name]; if(cityInfo){
response.json(cityInfo);
}else{
response.status(404).json("City not found");
}
});
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 cityInfo,
name;
name = request.params.name;
cityInfo = cities[name]; if(cityInfo){
response.json(cityInfo);
}else{
response.status(404).json("City not found");
}
}); app.listen(3000);

[Express] Level 3: Reading from the URL的更多相关文章

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

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

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

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

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

  4. [Express] Level 1: First Step

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

  5. Zabbix监控Low level discovery实时监控网站URL状态

    今天我们来聊一聊Low level discovery这个功能,我们为什么要用到loe level discovery这个功能呢? 很多时候,在使用zabbix监控一些东西,需要对类似于Itens进行 ...

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

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

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

  8. [Express] Level 3: Massaging User Data

    Flexible Routes Our current route only works when the city name argument matches exactly the propert ...

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

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

随机推荐

  1. tcpdump dns包(linux高性能编程读书笔记2)

      tcpdump -i eth0 -nt -s 500 port domain host -t A www.baidu.com www.baidu.com is an alias for www.a ...

  2. Pig Run on Hadoop, V1.0

    ——安装hadoop参考这篇blog: http://www.cnblogs.com/lanxuezaipiao/p/3525554.html?__=1a36 后面产生的问题,slave和master ...

  3. Android之操作SQLite

    一.SQLite的介绍 1.SQLite简介 SQLite是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入  式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的 ...

  4. LeetCode(2) - Add Two Numbers

    一道比较基本的LinkedList的题目.题目要求是这样,现在有两个LinkedList,(2  -> 4 -> 3)和(5 -> 6 -> 4),然后从头开始,把每个node ...

  5. Chapter 5 Convert Image Set To LevelDB/LMDB

    Caffe中convert_imageset projrct将图像数据转换成Caffe能读取的数据格式leveldb/lmdb 1.添加命令参数 在main函数中添加命令参数,内容和位置如下: #if ...

  6. 怎么监视跟踪一个进程(Process)中的MS Unit Test DLL的详细性能(performance)【asp.net C#】

    Sample This tutorial will show how to instrument a unit test DLL for performance profiling. Visual S ...

  7. mysql-python模块编译问题解决

    解决方法:yum -y install mysql-devel libxml2 libxml2-dev libxslt* zlib gcc openssl [root@localhost MySQL- ...

  8. LINQ标准查询操作符(四) —AsEnumerable,Cast,OfType,ToArray,ToDictionary,ToList,ToLookup,First,Last,ElementAt

    十.转换操作符 转换操作符是用来实现将输入对象的类型转变为序列的功能.名称以“As”开头的转换方法可更改源集合的静态类型但不枚举(延迟加载)此源集合.名称以“To”开头的方法可枚举(即时加载)源集合并 ...

  9. Unity3D Persistent Storage

    [Unity3D Persistent Storage] 1.PlayerPrefs类以键值对的形式来提供PersistentStorage能力.提供小额存储能力.(做成sst可以提供大规模数据存储) ...

  10. Oracle Standby Database 实现方案

    Oracle Standby Database 实现方案  From: http://wanow.blog.hexun.com/4672755_d.html 字号:大 中 小 版本:V20060328 ...