Express 是一个简洁而灵活的 node.js Web应用框架, 提供了一系列强大特性帮助你创建各种 Web 应用,和丰富的 HTTP 工具。
使用 Express 可以快速地搭建一个完整功能的网站。
Express 框架核心特性:
1. 可以设置中间件来响应 HTTP 请求。
2. 定义了路由表用于执行不同的 HTTP 请求动作。
3. 可以通过向模板传递参数来动态渲染 HTML 页面。
$ cnpm install body-parser --save
$ npm install body-parser --saveapi是
var bodyParser =
处理json 数据,buffer 数据, 文本数据,utf-8的编码数据。
bodyParser.json(options)、
bodyParser.raw(options)、
bodyParser.text(options)、
bodyParser.urlencoded(options)
底层中间件用法:
|
var
express = require(
'express'
)
var
bodyParser = require(
'body-parser'
)
var
app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended:
false
}))
// parse application/json
app.use(bodyParser.json())
app.use(
function
(req, res) {
res.setHeader(
'Content-Type'
,
'text/plain'
)
res.write(
'you posted:\n'
)
res.end(JSON.stringify(req.body,
null
, 2))
})
|
2、特定路由下的中间件用法:这种用法是针对特定路由下的特定请求的,只有请求该路由时,中间件才会拦截和解析该请求;也即这种用法是局部的;也是最常用的一个方式。
|
var
express = require(
'express'
)
var
bodyParser = require(
'body-parser'
)
var
app = express()
// create application/json parser
var
jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var
urlencodedParser = bodyParser.urlencoded({ extended:
false
})
// POST /login gets urlencoded bodies
app.post(
'/login'
, urlencodedParser,
function
(req, res) {
if
(!req.body)
return
res.sendStatus(400)
res.send(
'welcome, '
+ req.body.username)
})
// POST /api/users gets JSON bodies
app.post(
'/api/users'
, jsonParser,
function
(req, res) {
if
(!req.body)
return
res.sendStatus(400)
// create user in req.body
})
|
express的post(或者get)方法调用body-parser实例;且该方法有设置路由路径;这样的body-parser实例就会对该post(或者get)的请求进行拦截和解析。
3、设置Content-Type 属性;用于修改和设定中间件解析的body类容类型。
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' });
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));

276

被折叠的 条评论
为什么被折叠?



