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. Hive QL

    转自http://www.alidata.org/archives/581 Hive 的官方文档中对查询语言有了很详细的描述,请参考:http://wiki.apache.org/hadoop/Hiv ...

  2. yum 安装 php5.6 和 mysql5.6

    安装 PHP rpm -Uvh http://ftp.iij.ad.jp/pub/linux/fedora/epel/6/i386/epel-release-6-8.noarch.rpm; rpm - ...

  3. 客户端无法tcp连接上本地虚拟机的问题(最后是linux防火墙问题)

    刚装好裸的centos6.5,很多东西跟以前比都是没有的,所以做起来会遇到很多问题. 今天刚把svn 无法ci的问题解决了,起完服后,发现客户端连不上. 1)端口转发,查看了一下虚拟机的端口转发,发现 ...

  4. XSS攻击及防御(转)

    add by zhj: 略有修改.另外还有一篇文章值得参考,使用 PHP 构建的 Web 应用如何避免 XSS 攻击,总得来说防御XSS的方法是客户端和服务端都 要对输入做检查,如果只有客户端做检查, ...

  5. java之四大皆空

    SE中的所有空的情况: 第一空:定义变量,变量没有值不能使用,不能打印 public class DiDaJieKong01 { public static void main(String[] ar ...

  6. lua学习:游戏中的Lua

    lua作为一种脚本语言,可以快速地开发游戏的原型.提高游戏的开发效率. 在游戏中,lua可以用来完成下面这些工作: ●编辑游戏的用户界面 ●定义.存储和管理基础游戏数据 ●管理实时游戏事件 ●创建和维 ...

  7. chrome emulator use-agent 设置 chrom模拟手机客户端

    谷歌升级以后,发现找不到use-agent设置了 在Element 下点击ESC 出现console,再点击Emulation就出现了

  8. KMP算法及java实现

    参考: http://blog.csdn.net/cdnight/article/details/11935387

  9. ASP.NET MVC 4 中Jquery上传插件Uploadify简单使用-版本:3.2.1

    1.官网下载开发包:http://www.uploadify.com/download/,选择免费的Flash版本: 2.解压后,需要用到以下几个文件: 需要修改uploadify.css中取消上传按 ...

  10. ASP.NET设置404页面返回302HTTP状态码的解决方法

    在配置文件中配置404页面如下: .代码如下: <customErrors mode="On" defaultRedirect="404.aspx"> ...