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. Shapefile文件中的坐标绘制到屏幕时的映射模式设置

    pDC->SetMapMode(MM_ANISOTROPIC ); //首先选择MM_ANISOTROPIC映射模式,其它映射模式都不合适 pDC->SetWindowExt( max(a ...

  2. webstorm无法格式化

    快捷键失效,一般都是由于快键键冲突引起的.但是像CTRL + ALT + L的组合件冲突,还是没见过. 后来在网上查知,网易云音乐,会引发此冲突,果然高手在网络啊. 打开设置,禁用网易云音乐快捷键,妥 ...

  3. 【LeetCode】66 & 67- Plus One & Add Binary

    66 - Plus One Given a non-negative number represented as an array of digits, plus one to the number. ...

  4. Swift相关图书推荐

    Swift与Cocoa框架开发 作      者 [澳] 曼宁(Jonathon Manning),巴特菲尔德-艾迪生(Paris Buttfield 出 版 社 人民邮电出版社 出版时间 2015- ...

  5. Linux 下C++编写

    今天搞了一天Linux下C++编程,还没有什么成效.好烦躁好心焦,想砸电脑的冲动.抽根烟理下思路一定要把它拿下!! ===搞了两天,真是搞到生无可恋,试了共享文件, 试了网络配置,各种博客就是各种行不 ...

  6. MapReduce阅读

    1.mongodb权威指南6.4章 2.百科:http://baike.baidu.com/link?url=fl9FwgNq7gtFLwJ-GuKsJ25Uk-wnhgDjEwkKd8-5hoIkh ...

  7. HW7.12

    import java.util.Scanner; public class Solution { public static void main(String[] args) { double[] ...

  8. 每天学一点-Jquery判断checkbox是否为选中状态

    if ($("#ctl00_ContentPlaceHolder1_IsLimitedService").attr("checked") ==true)

  9. Network Object NAT配置介绍

    1.Dynamic NAT(动态NAT,动态一对一) 实例一: 传统配置方法: nat (Inside) 1 10.1.1.0 255.255.255.0 global (Outside) 1 202 ...

  10. UVaLive 6801 Sequence (计数DP)

    题意:给定一个序列,有 n 个数,只有01,然后你进行k次操作,把所有的1变成0,求有多种方法. 析:DP是很明显的,dp[i][j] 表示进行第 i 次操作,剩下 j 个1,然后操作就两种,把1变成 ...