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. JavaScript高级程序设计(第三版)第二章 在HTML中使用JavaScript

    2.1 <script>元素 <script>定义了下列6个属性: async:可选.表示应该立即下载脚本,但不应妨碍页面的其他操作,比如下载其他资源或等待加载其他脚本.只对外 ...

  2. Android Capture Android System Audio

    项目需要获取播放视频的实时音量值,最简捷的方法是监听音频输出端,取得音频输出流,再进行转换. 调查时,首先找到这篇博客: http://blog.csdn.net/jinzhuojun/article ...

  3. 利用 Oracle EM 企业管理器 进行oracle SQL的优化(自动生成索引)

    利用 Oracle EM 企业管理器 进行oracle SQL的优化(自动生成索引) ##应用情景 项目中有大量的SQL,尤其是涉及到统计报表时,表关联比较多,当初开发建表时也没搞好索引关联的,上线后 ...

  4. HDU ACM 1050 Moving Tables

    Problem Description The famous ACM (Advanced Computer Maker) Company has rented a floor of a buildin ...

  5. BitmapData类介绍

    今天介绍另外一个比较常用和中高级难度的类:BitmapData 用好这个类,可以说是半支脚踏入了Flash高手的大门···(主要是不是太多的人精通这个··呵呵··)我也可以趁这篇文章的机会好好巩固+学 ...

  6. js运动 淡入淡出

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  7. forms

    http://www.cnblogs.com/bomo/p/3309766.html http://www.cnblogs.com/leonwang/archive/2013/03/05/294457 ...

  8. Unix 环境高级编程---线程创建、同步、

    一下代码主要实现了linux下线程创建的基本方法,这些都是使用默认属性的.以后有机会再探讨自定义属性的情况.主要是为了练习三种基本的线程同步方法:互斥.读写锁以及条件变量. #include < ...

  9. compiled python files

    [compiled python files] As an important speed-up of the start-up time for short programs that use a ...

  10. Python的高级Git库 Gittle

    Gittle是一个高级纯python git 库.构建在dulwich之上,提供了大部分的低层机制 Gittle是一个高级纯python git 库.构建在dulwich之上,提供了大部分的低层机制. ...