express html文件接收路由参数,express 获取post 请求参数
在 Express 中沒有內(nèi)置獲取表單 POST 請(qǐng)求體的 API , 我們需要添加第三方插件庫
安裝:
npm install --save body-parser
配置:
var bodyParser = require('body-parser')
//配置 body-parser 中間件 (插件, 專門用來解析表單 POST 請(qǐng)求)
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({txtended: false}))
//parse application/json
app.use(bodyParser.json())
實(shí)例:
var express = require('express')
var bodyParser = require('body-parser')
//1. 創(chuàng)建app
var app = express()
/*
* 第一個(gè)參數(shù) 表示, 當(dāng)渲染以 .art 結(jié)尾的文件時(shí)候 使用 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 相應(yīng)對(duì)象提供一個(gè)方法 : render
* render 方法默認(rèn)不可以使用, 但是如果配置了模板引擎就可以
* res.render('html模板名','模板數(shù)據(jù)')
* 第一個(gè)參數(shù)不能寫路徑 , 默認(rèn)會(huì)去項(xiàng)目中的views 目錄匯總找模板文件
* 也就是 Express 有一個(gè)約定, 開發(fā)人員把所有的視圖文件都放到 views 文件中
*/
var comments = [
{
name: '張三',
message: '今天天氣不錯(cuò)',
dateTime: '2019-10-16'
},
{
name: '張三2',
message: '今天天氣不錯(cuò)',
dateTime: '2019-10-16'
},
{
name: '張三3',
message: '今天天氣不錯(cuò)',
dateTime: '2019-10-16'
},
{
name: '張三4',
message: '今天天氣不錯(cuò)',
dateTime: '2019-10-16'
},
{
name: '張三5',
message: '今天天氣不錯(cuò)',
dateTime: '2019-10-16'
}
]
//配置 body-parser 中間件 (插件, 專門用來解析表單 POST 請(qǐng)求)
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({txtended: false}))
//parse application/json
app.use(bodyParser.json())
// 如果要修改 views 目錄
//app.set('views', 'render函數(shù)的默認(rèn)路徑')
app.get('/404', function (req, res) {
res.render('404.html')
})
app.get('/admin', function (req, res) {
res.render('admin/index.html', {
title: '管理系統(tǒng)'
})
})
//設(shè)置靜態(tài)文件路經(jīng) 用/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 請(qǐng)求參數(shù)
* 處理
* 發(fā)送響應(yīng)
*/
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...' )
})
總結(jié)
以上是生活随笔為你收集整理的express html文件接收路由参数,express 获取post 请求参数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nfc sim android8,And
- 下一篇: php密码怎么用md5,如何使用PHP使