[Express] Level 4: Body-parser -- Post
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 betweenqsandquerystringand 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的更多相关文章
- [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 ...
- [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 ...
- [Express] Level 4: Body-parser -- Delete
Response Body What would the response body be set to on a DELETE request to /cities/DoesNotExist ? H ...
- [Express] Level 3: Massaging User Data
Flexible Routes Our current route only works when the city name argument matches exactly the propert ...
- [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 ...
- [Express] Level 2: Middleware -- 2
Logging Middleware Help finish the following middleware code in the logger.js file: On the response ...
- [Express] Level 2: Middleware -- 1
Mounting Middleware Given an application instance is set to the app variable, which of the following ...
- [Express] Level 1: First Step
Installing Express Let's start building our new Express application by installing Express. Type the ...
- 基于express框架的应用程序骨架生成器介绍
作者:zhanhailiang 日期:2014-11-09 本文将介绍怎样使用express-generator工具高速生成基于express框架的应用程序骨架: 1. 安装express-gener ...
随机推荐
- Windows8.1 安装office2013并激活
之前笔记本上安装的东西太多了,启动比较慢,打算重做系统,正好同事有一个Windows8.1的系统盘,直接做了一个Windows8.1的系统.界面清爽,速度还可以,系统安装完成以后,准备安装office ...
- 千万别把js的正则表达式方法和字符串方法搞混淆了
我们在字符串操作过程中肯定经常用了test() split() replace() match() indexof()等方法,很多人经常把用法写错了,包括我,所以今天细细的整理了下. test()是判 ...
- AS3垃圾回收整理
AS3垃圾回收整理 转自 http://bbs.wefdc.com/thread-2366-1-1.html 来源页面: http://www.adobe.com/devnet/actionscrip ...
- TintTo和TintBy
//创建标签 ); //设置位置 helloLabel.setPosition(cc.p(,)); //添加到layer ); //改变颜色,不可reverse ,,); //移动并同时改变颜色 he ...
- MYSQL数据库性能调优之三:explain分析慢查询
explain显示了mysql如何使用索引来处理select语句以及连接表.可以帮助选择更好的索引和写出更优化的查询语句.使用方法,在select语句前加上explain就可以了. 一.explain ...
- VS2010在C#头文件添加文件注释的方法(转)
步骤: 1.VS2010 中找到(安装盘符以C盘为例)C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplatesCa ...
- find命令之exec
find是我们很常用的一个Linux命令,但是我们一般查找出来的并不仅仅是看看而已,还会有进一步的操作,这个时候exec的作用就显现出来了. exec解释: -exec 参数后面跟的是command ...
- Objective C静态代码扫描和代码质量管理 OClint + SonarQube
OClint是针对C, C++及Objective C代码的静态扫描分析工具,而SonarQube是一个开源的代码质量管理平台.本文将实现将OClint的扫描结果导入到SonarQube中,已实现对O ...
- RPG JS:免费开源的跨平台RPG游戏引擎
RPG JS是一个2D RPG游戏制作引擎,目前版本基于Ease|JS游戏引擎,基于Canvas Engine的新版本即将发布. RPG JS是免费且开源的. RPG JS有着完善的文档支持. RPG ...
- MD5加密类方法
package com.shkj.android.utils; import java.security.MessageDigest;import java.security.NoSuchAlgori ...