Express_02--处理表单的POST请求

简介: Express_02--处理表单的POST请求

express处理表单的post请求

需要我们注意的是express内置了获取get请求体的API(req.query),但是并没有内置获取post请求体的API,所以需要我们手动的去配置中间件。

配置body-parser中间件

1. 安装

npm install body-parser
复制代码

2. 导入并配置

const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
复制代码

3. 此时即可成功获取req.body(客户端post的内容)

app.post('/post',(req,res) => {
    console.log(req.body);
})
复制代码
[Object: null prototype] { name: 'faithpassi', message: 'dsddfgfgdf' }
复制代码

将读取到的字符串转为JSON

fs.readFile('./db.json','utf8', (err, data) => {
    if (!err) {
        res.render('index.html', {
            students: JSON.parse(data).students
        });
    }
})
复制代码

将所有的路由结构提取到一个文件中,并进行暴露

方式一:自己封装函数

const fs = require('fs');
module.exports = function (app) {
    app.get('/students', (req, res) => {
        fs.readFile('./db.json', 'utf8', (err, data) => {
            if (!err) {
                res.render('index.html', {
                    students: JSON.parse(data).students
                });
            }
        })
    })
}
复制代码

方式二:使用Express自带的路由容器

1.在路由文件中创建路由容器,并进行暴露

const express = require('express');
// 创建一个路由容器
const router = express.Router();
router.get('/students', (req, res) => {
    fs.readFile('./db.json', 'utf8', (err, data) => {
        if (!err) {
            res.render('index.html', {
                students: JSON.parse(data).students
            });
        }
    })
})
module.exports = router;
复制代码

2. 将路由容器挂载到app上

// 把路由器挂载到 app上
app.use(router)


相关文章
|
5月前
|
前端开发
ajax设置header
ajax设置header
|
4月前
|
Web App开发 前端开发 JavaScript
AJAX POST请求中参数以form data和request payload形式在servlet中的获取方式
AJAX POST请求中参数以form data和request payload形式在servlet中的获取方式
32 0
|
4月前
【Express】—post传递参数
【Express】—post传递参数
|
10月前
|
JavaScript 前端开发
Form表单利用Jquery Validate验证以及ajax提交
Form表单利用Jquery Validate验证以及ajax提交
50 0
|
11月前
|
前端开发
Ajax基本案例详解之$.post的实现
Ajax基本案例详解之$.post的实现
51 0
express学习46-ajax实现步骤
express学习46-ajax实现步骤
74 0
express学习46-ajax实现步骤
express学习7-express参数中post参数的获取
express学习7-express参数中post参数的获取
200 0
express学习7-express参数中post参数的获取
|
JavaScript 前端开发 PHP
jquery $.post 序列化表单ajax提交
jquery $.post 序列化表单ajax提交
95 0
Ajax-03:Express基本使用
Ajax-03:Express基本使用
80 0