[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 ...
随机推荐
- WebSocket with Flask
转自:https://blog.shonenada.com/post/websocket-with-flask/ WebSocket with Flask HTML5 以前,HTML 还不支持 Web ...
- Java多线程学习总结--线程概述及创建线程的方式(1)
在Java开发中,多线程是很常用的,用得好的话,可以提高程序的性能. 首先先来看一下线程和进程的区别: 1,一个应用程序就是一个进程,一个进程中有一个或多个线程.一个进程至少要有一个主线程.线程可以看 ...
- 为operamasks增加HTML扩展方式的组件调用
#为operamasks增加HTML扩展方式的组件调用 ##背景 之前的[博文](http://www.cnblogs.com/p2227/p/3540858.html)中有提及到,发现easyui中 ...
- Numpy矩阵取列向量
>>> A=matrix("1 2;3 4") >>> A matrix([[1, 2], [3, 4]]) >>> A[:, ...
- 《学习OpenCV》练习题第四章第一题a
#include <highgui.h> #include <cv.h> #pragma comment (lib,"opencv_calib3d231d.lib&q ...
- geeksforgeeks@ Find sum of different corresponding bits for all pairs (Bit manipulation)
http://www.practice.geeksforgeeks.org/problem-page.php?pid=387 Find sum of different corresponding b ...
- Linux下动态库生成和使用
Linux下动态库生成和使用 一.动态库的基本概念 1.动态链接库是程序运行时加载的库,当动态链接库正确安装后,所有的程序都可以使用动态库来运行程序.动态链接库是目标文件的集合,目标文件在动态链接库中 ...
- visualC/C++连接MySql数据库
vs连接数据库其实就是将mysql数据库.h头文件接口.lib链接文件和dll执行文件加入到项目中.下面是配置如何加入. 转于http://www.cnblogs.com/justinzhang/ar ...
- mac电脑Coding显示/隐藏文件
苹果Mac OS X操作系统下,隐藏文件是否显示有很多种设置方法,最简单的要算在Mac终端输入命令.显示/隐藏Mac隐藏文件命令如下(注意其中的空格并且区分大小写): 显示Mac隐藏文件的命令:def ...
- 字符编解码的故事(ASCII,ANSI,Unicode,Utf-8)
很久很久以前,有一群人,他们决定用8个可以开合的晶体管来组合成不同的状态,以表示世界上的万物.他们认为8个开关状态作为原子单位很好,于是他们把这称为"字节". 再后来,他们又做了一 ...