[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 ...
随机推荐
- C#判断程序是由Windows服务启动还是用户启动
在Windows系统做网络开发,很多时候都是使用Windows服务的模式,但在调度阶段,我们更多的是使用控制台的模式.在开发程序的时候,我们在Program的Main入口进行判断.最初开始使用Envi ...
- 写好Hive 程序的五个提示
转自http://www.alidata.org/archives/622 使用Hive可以高效而又快速地编写复杂的MapReduce查询逻辑.但是某些情况下,因为不熟悉数据特性,或没有遵循Hive的 ...
- 分享一些前端chm文档
分享地址:http://yun.baidu.com/share/link?shareid=39230983&uk=1008683945 对于网络不好的人来说,离线文档更加方便.打开速度更快. ...
- c# webbrowser获取滚动条最大值
int HeightMax = 0; int WidthMax =0; HeightMax = webBrowser1.Document.Body.ScrollRectangle.Height-web ...
- eclipse gradle 自动打包
直接在eclipse项目中建立一个文件,文件名为build.gradle.其实还可以用eclipse再项目上面右击,export->Android->Generate Gradle bui ...
- Hbase学习记录(2)| Shell操作
查看表结构 describe '表名' 查看版本 get '表名','zhangsan'{COLUMN=>'info:age',VERSIONS=>3} 删除整行 deleteall '表 ...
- javascript面向对象事件继承
继承:父类有的,子类也有.父类改变,子类也跟着变. 属性继承: 矫正this (window对象,矫正成object对象) fn .call(this是谁,参数1,参数2...); ...
- SharePoint咨询师之路:设计之前的那些事一:容量
提示:本系列只是一个学习笔记系列,大部分内容都可以从微软官方网站找到,本人只是按照自己的学习路径来学习和呈现这些知识. 咨询师更多的时候是解决方案提供者,那么他们如何能够提供有效的SharePoint ...
- 【转】MySQL索引和查询优化
原文链接:http://www.cnblogs.com/mailingfeng/archive/2012/09/26/2704344.html 对于任何DBMS,索引都是进行优化的最主要的因素.对于少 ...
- pureMVC学习之一
//1var MainWindow: TMainWindow;begin Application.Initialize; Application.MainFormOnTaskbar := Tru ...