• [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');

    The body-parser middleware offers different parsing options. On thebodyParser object, call a function that returns a parser for URL encoded data and store it in a variable called parseUrlencoded. Remember to pass in an option which forces the use of the native querystring Node library.

    var parseUrlencoded = bodyParser.urlencoded({extended: false});
    • extended - parse extended syntax with the qs module. (default: true, but using the default has been deprecated. Please research into the difference between qs and querystring and choose the appropriate setting)

    For default qs model: https://www.npmjs.org/package/qs#readme

    var obj = Qs.parse('a=c');    // { a: 'c' }

    Read More: https://github.com/expressjs/body-parser

    Mount the parser only in the post route.

    app.post('/cities',parseUrlencoded, function (request, response) {
      var city;
    });

    Read the name and description parameters from the payload of the POSTrequest, and pass them as arguments to the createCity function (we've created this one for you). Store the return value on the city variable.

    app.post('/cities',parseUrlencoded, function (request, response) {
      var city, name, description;
      city = request.body;
      name = city.name;
      description = city.description;
      createCity(name, description);
    });

    Finally, respond back to the client with a 201 HTTP status code and the value stored in city in JSON format using json.

    app.post('/cities',parseUrlencoded, function (request, response) {
      var city, name, description, cityName;
      city = request.body;
      name = city.name;
      description = city.description;
      cityName = createCity(name, description);
      response.status(201).json(cityName); //201: created
    });
    var express = require('express');
    var app = express();
    var bodyParser = require('body-parser');
    var parseUrlencoded = bodyParser.urlencoded({extended: false});
    
    app.post('/cities',parseUrlencoded, function (request, response) {
      var city, name, description, cityName;
      city = request.body;
      name = city.name;
      description = city.description;
      cityName = createCity(name, description);
      response.status(201).json(cityName); //201: created
    });
    
    app.listen(3000);
    
    var createCity = function(name, description){
      cities[name] = description;
      return name; 
    };

    Validation

    The way that it is now, we are allowing new cities to be created with a blank description. Let's add some validation so that in order for a city to be created, its description must have a string length greater than 4.

    Add an if block that checks for a description.length greater than 4, and move our city creation logic into that block. Use json() to send the results from createCity back to the client.

      if(request.body.description.length > 4){
        var city = createCity(request.body.name, request.body.description);
          response.status(201).json(city);
      } 

    If description does not match its minimum length requirements, then set a400 status code (Bad Request) to the response, and set the response body toInvalid City using json().

    app.post('/cities', parseUrlencoded, function (request, response) {
      
      if(request.body.description.length > 4){
        var city = createCity(request.body.name, request.body.description);
          response.status(201).json(city);
      }else{
        response.status(400).json("Invalid City"); //400: bad request
      }
    });
    var express = require('express');
    var app = express();
    
    var bodyParser = require('body-parser');
    var parseUrlencoded = bodyParser.urlencoded({ extended: false });
    
    app.post('/cities', parseUrlencoded, function (request, response) {
      
      if(request.body.description.length > 4){
        var city = createCity(request.body.name, request.body.description);
          response.status(201).json(city);
      }else{
        response.status(400).json("Invalid City"); //400: bad request
      }
    });
    
    app.listen(3000);
  • 相关阅读:
    CentOS7安装docker
    CentOS7安装maven
    centos下使用ifconfig命令无法得到ip地址的解决方案
    Elasticsearch 2.3.5 之Head插件安装
    CentOS7中yum源结构解析
    EXT.NET Combox下拉Grid
    转 Refresh Excel Pivot Tables Automatically Using SSIS Script Task
    SQL Server Integration Services SSIS最佳实践
    PowerBI
    [XAF] Llamachant Framework Modules
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4143493.html
Copyright © 2020-2023  润新知