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. OpenGl从零开始之坐标变换(上)

    坐标变换是深入理解三维世界的基础,非常重要.学习这部分首先要清楚几个概念:视点变换.模型变换.投影变换.视口变换. 在现实世界中,所有的物体都具有三维特征,但计算机本身只能处理数字,显示二维的图形,因 ...

  2. 【Unity入门】编辑器常用视图介绍

    版权声明:本文为博主原创文章,转载请注明出处. 打开Unity编辑器的主窗口,在窗口的右上角可以看到有个“Layout”按钮.这是用来对Unity编辑器主窗口上面的各个窗口面板进行布局的.通常情况下我 ...

  3. js和jquery实现tab选项卡

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. 分享一些前端chm文档

    分享地址:http://yun.baidu.com/share/link?shareid=39230983&uk=1008683945 对于网络不好的人来说,离线文档更加方便.打开速度更快. ...

  5. [转] Web 前端优化最佳实践之 Mobile(iPhone) 篇

    原文链接:http://dbanotes.net/web/best_practices_for_speeding_up_your_web_site_server_mobile.html Web 前端优 ...

  6. 使用Log.isLoggable方法

    在Audio Debug过程中想打开AudioService.java文件中的log,比如想打开setmode这段log: if (DEBUG_MODE) { Log.v(TAG, "set ...

  7. 20151227感知机(perceptron)

    1 感知机 1.1 感知机定义 感知机是一个二分类的线性分类模型,其生成一个分离超平面将实例的特征向量,输出为+1,-1.导入基于误分类的损失函数,利用梯度下降法对损失函数极小化,从而求得此超平面,该 ...

  8. JVM内存的那些事

    前言 对于C语言开发的程序员来说,在内存管理方面,必须负责每一个对象的生命周期,从有到无. 对于Java程序员你来说,在虚拟机内存管理的帮助下,不需要为每个new对象都匹配free操作,内存泄露和内存 ...

  9. USB2.0规范

    USB是一种支持热插拔的高速串行传输总线,它使用差分信号来传输数据,最高速度可达480Mb/S. USB支持“总线供电”和“自供电”两种供电模式.在总线供电模式下,设备最多可以获得500mA的电流.U ...

  10. scp,ssh双机互信操作步骤

     Node1:# ssh-keygen -t rsa 这一步是生成密钥# ssh-copy-id -i ~/.ssh/id_rsa.pub root@node2.xueping365.com ~/.s ...