express 获取post 请求参数

在 Express 中没有内置获取表单 POST 请求体的 API , 我们需要添加第三方插件库

安装:

npm install --save body-parser

配置:

var bodyParser = require('body-parser')

//配置 body-parser 中间件 (插件, 专门用来解析表单 POST 请求)
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({txtended: false}))
//parse application/json
app.use(bodyParser.json())

  

 实例:

var express = require('express')
var bodyParser = require('body-parser')
//1. 创建app
var app = express()

/*
 * 第一个参数 表示, 当渲染以 .art 结尾的文件时候 使用 art-template 模板引擎
 * express-art-template 是专门用来 Express 中把 art-template 整合到 Express  
 * 虽然不需要加载 art-template   但也必须要安装
 */

//app.engine( 'art', require('express-art-template') )
app.engine( 'html', require('express-art-template') )

/*
 * Express 为 Response 相应对象提供一个方法 : render
 * render 方法默认不可以使用, 但是如果配置了模板引擎就可以
 * res.render('html模板名','模板数据')
 * 第一个参数不能写路径 , 默认会去项目中的views 目录汇总找模板文件
 * 也就是 Express 有一个约定, 开发人员把所有的视图文件都放到 views 文件中
 */

var comments = [
	{
		name: '张三',
		message: '今天天气不错',
		dateTime: '2019-10-16'
	},
	{
		name: '张三2',
		message: '今天天气不错',
		dateTime: '2019-10-16'
	},
	{
		name: '张三3',
		message: '今天天气不错',
		dateTime: '2019-10-16'
	},
	{
		name: '张三4',
		message: '今天天气不错',
		dateTime: '2019-10-16'
	},
	{
		name: '张三5',
		message: '今天天气不错',
		dateTime: '2019-10-16'
	}
]


//配置 body-parser 中间件 (插件, 专门用来解析表单 POST 请求)
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({txtended: false}))
//parse application/json
app.use(bodyParser.json())


// 如果要修改 views 目录
//app.set('views', 'render函数的默认路径')

app.get('/404', function (req, res) {
	res.render('404.html')
})

app.get('/admin', function (req, res) {
	res.render('admin/index.html', {
		title: '管理系统'
	})
})

//设置静态文件路经  用/public/ 代替  './public/'
app.use('/public/', express.static('./public/') )

app.get('/', function (req, res) {

	//res.end('hello world') 
	res.render('index.html', {
		comments: comments
	})

})

app.get('/post', function (req, res) {

	res.render('post.html')

})

app.get('/pinglun', function (req, res) {

	var comment = req.query
	comment.dateTime = '2019-11-02 17:17:17'
	//comments.push(comment)
	comments.unshift(comment)
	res.redirect('/')
})

app.post('/pinglun', function (req, res) {
	/*
	 * 获取 post 请求参数
	 * 处理
	 * 发送响应
	 */
	var comment = req.body
	comment.dateTime = '2019-11-02 17:17:17'
	//comments.push(comment)
	comments.unshift(comment)
	res.redirect('/')

})

app.listen(3000, function () {
	console.log( 'express app is running...' )
})

  

原文地址:https://www.cnblogs.com/jasonLiu2018/p/11218026.html