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. bzoj 1806 [Ioi2007]Miners 矿工配餐(DP)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1806 [题意] 给定一个权在1..3内的序列,在保持相对位置不变的情况下拆分成两个序列 ...

  2. 【Python学习笔记】字符串操作

    字符串的表示 python中的字符串是一个常量,可以使用单引号'',双引号""或三引号""" """来创建一个字符串常量 ...

  3. Windows Azure存储容器私有,公共容器,公共Blob的区别

    当我们在Windows Azure中创建或编辑存储的容器时,需要选择访问类型,本文将描述一下这三个选项的区别. 1. 私有: 默认选项,顾名思义,用户不能通过URL匿名进行访问容器或容器内的任何Blo ...

  4. sqlserver安装相关问题

    最近在部署一个工程,数据库(sqlserver2005develop)遇到不少问题,下面将一一列出. 安装完毕后,无法连接到本地实例. 打开microsoft sql server 2005-> ...

  5. Android将ScrollView移动到最底部

    转载地址:http://hi.baidu.com/gaogaf/item/36e8a4c8ac6ba31050505848 scrollTo方法可以调整view的显示位置.在需要的地方调用以下方法即可 ...

  6. 【360开源】thinkjs:基于Promise的Node.js MVC框架 (转)

    thinkjs是360奇舞团开源的一款Node.js MVC框架,该框架底层基于Promise来实现,很好的解决了Node.js里异步回调的问题.360奇舞团(奇虎75Team),是奇虎360公司We ...

  7. ActiveX控件

    什么是ActiveX控件:一个进程内服务器,支持多种的COM接口.(可以理解为,一个COM接口是一个纯抽象基类,你实现了它,并且它支持自注册,就是一个ActiveX控件了)可以把ActiveX控件看做 ...

  8. hdu 2444 The Accomodation of Students(最大匹配 + 二分图判断)

    http://acm.hdu.edu.cn/showproblem.php?pid=2444 The Accomodation of Students Time Limit:1000MS     Me ...

  9. C# 与 C++ 数据类型对照

    C++            C#=====================================WORD            ushortDWORD            uintUCH ...

  10. JVM启动参数小结

    一:JVM启动参数共分为三类:         其一是标准参数(-),所有的JVM实现都必须实现这些参数的功能,而且向后兼容:        其二是非标准参数(-X),指的是JVM底层的一些配置参数, ...