[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 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);
时间: 2024-11-05 02:48:26

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

[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 for the '/cities' URL path and assign it to thecitiesRoute variable. var citiesRoute = app.route('/cities'); Move the code from our previous app.get() 

[Express] Level 2: Middleware -- 1

Mounting Middleware Given an application instance is set to the app variable, which of the following function calls would you use to mount a middleware called logger ? Answer: app.use(logger); Default Middleware What is the only middleware that's shi

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

Parser Setup Assume the body-parser middleware is installed. Now, let's use it in our Express application. npm install body-parser Require the body-parser npm module and assign it to a variable calledbodyParser. var bodyParser = require('body-parser'

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

今天我们来聊一聊Low level discovery这个功能,我们为什么要用到loe level discovery这个功能呢? 很多时候,在使用zabbix监控一些东西,需要对类似于Itens进行添加,这些items具有一些共同特性, 如果说某些特定的参数是变量,而其他设置都一样,例如:一个程序有多个端口,需要多端口进行监控并配置Itmes,还有磁盘分区,·网卡名称等等, 都是具有不确定性,如果我们配置固定的Items的话,会出现无法通用的问题,所以呢,我们需要来了解一下low level 

[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 assign it to the router variable. var router = express.Router(); When we are done, our router will be mounted on the /cities path. With this in mind,

[Express] Level 2: Middleware -- 2

Logging Middleware Help finish the following middleware code in the logger.js file: On the response object, listen to the event that's emitted when the response has been handed off from Express to the underlying Operating System. response.on('finish'

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

Response Body What would the response body be set to on a DELETE request to /cities/DoesNotExist ? Here's the link to the sendStatus function source code if you need to take a look. Answer: 404 Delete Route Create a Dynamic Route for deleting cities

[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

NodeJS 入门第三天(Express框架)

一.Express框架 Express框架是后台的Node框架,所以和jQuery.zepto.yui.bootstrap都不一个东西. Express在后台的受欢迎的程度,和jQuery一样,就是企业的事实上的标准. ● 原生Node开发,会发现有很多问题.比如: ■ 呈递静态页面很不方便,需要处理每个HTTP请求,还要考虑304问题 ■ 路由处理代码不直观清晰,需要写很多正则表达式和字符串函数 ■ 不能集中精力写业务,要考虑很多其他的东西 我们自己可以把第一天的作业,就是那个静态文件服务给封