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);

[Express] Level 4: Body-parser -- Post的更多相关文章

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

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

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

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

  4. [Express] Level 3: Massaging User Data

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

  5. [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 t ...

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

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

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

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

  8. [Express] Level 1: First Step

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

  9. 基于express框架的应用程序骨架生成器介绍

    作者:zhanhailiang 日期:2014-11-09 本文将介绍怎样使用express-generator工具高速生成基于express框架的应用程序骨架: 1. 安装express-gener ...

随机推荐

  1. 第三方框架之ThinkAndroid 学习总结(一)

    ThinkAndroid是一个免费的开源的.简易的.遵循Apache2开源协议发布的Android开发框架,其开发宗旨是简单.快速的进行Android应用程序的开发,包含Android mvc.简易s ...

  2. AlertDialog对话框简单案例

    什么是Dialog? Dialog类,是一切对话框的基类,需要注意的是,Dialog类虽然可以在界面上显示,但是并非继承于View类,而是直接从java.lang.Object开始构造出的.类似于Ac ...

  3. ABP的语言切换

    在ABP官网http://www.aspnetboilerplate.com/创建一个Multi Page Web Application项目并打开,在Web项目下可以找到一个Controllers/ ...

  4. 【openGL】四面体

  5. MySQL数据库服务器的架设

    导读 MySQL数据库是Linux操作系统上用得最多的数据库系统,它可以非常方便的与其它服务器集成在一起,如Apache.Vsftpd.Postfix等.下面介绍RHEL 6平台MySQL数据库服务器 ...

  6. Sublime3基础使用技巧

    1.安装SideBarEnhancements插件 ctrl+shift+p —> Install Package —> 找到SideBarEnhancements 2.安装CSS调色器: ...

  7. mysql if条件

    #if表达式 SELECT reg_no, IF(reg_no='718170554','黄色宾利','红色宾利') FROM car WHERE reg_no IN ('718170554','12 ...

  8. VC++ 网络编程总结(二)

    2.基本的Windows Socket API编程 需要在程序中添加下面的包含语句:#include <winsock2.h>   #pragma comment( lib, " ...

  9. WPF button 如何区分click和doubleclick

    WPF button 同时处理两个事件时候会先触发click事件,触发doubleclick事件  ,那如何区分呢,可以这样设置: private static DispatcherTimer myC ...

  10. Security log is full,only administrator can log on to fix the problem(安全日志满了)

    When you login the system and see this error  “Security log on this system is full,only administrato ...