zoukankan      html  css  js  c++  java
  • [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:

  • 相关阅读:
    软件部门每年耗资大约100亿到200多亿美元,但没有研发出任何具有说服力的产品,因此华为决定关闭
    Qt Model/View理解(二)---构造model(细心研读,发现超简单,Model就是做三件事:返回行数量、列数量、data如何显示。然后把model与view联系起来即可,两个例子都是如此)good
    linux 下用find命令查找文件,rm命令删除文件
    北电之死:谁谋杀了华为的对手?——银湖资本(Silver Lake)董事总经理爱德华·詹德出任CEO,既不了解华为,也不重视中国,直截了当地否决了收购华为
    搞定JavaScript正则表达式
    Orleans3.0
    CSS盒模型
    作用域和闭包
    NServiceBus是.Net平台下的开源的消息服务框架
    [1]System.Reflection.Emit
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4143408.html
Copyright © 2011-2022 走看看