处理post请求
npm i body-parser
const express = require("express")
const server = express()
const bodyParser = require("body-parser")
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json())
1、使用post请求
// 2.新增
router.post('/finishProduct/add', (req, res) => {
const uuid = uuidv4().split('-').join("")
const {
name,
bindProps = [],
bindPropsId = [],
propsTable = [],
talentId = '',
} = req.body;
const createTime = moment().format('YYYY-MM-DD HH:mm:ss')
const sqlStr = `INSERT INTO finishProduct (id, name, bindProps, bindPropsId, propsTable, talentId, createTime) VALUES ('${uuid}', '${name}', '${JSON.stringify(bindProps)}', '${JSON.stringify(bindPropsId)}', '${JSON.stringify(propsTable)}', '${talentId}', '${createTime}')`
conn.query(sqlStr, (err, result) => {
console.log(err);
if (err) {
res.json({
"code": 1,
"message": "新增成品失败!"
})
return;
}
res.json({
"code": 0,
"message": "新增成品成功!"
})
})
})
:::info
对于数组、对象这些类型需要JSON.stringify成字符串,不然入库的时候格式不对
:::
2、get获取上面新增的数据
router.get('/finishProduct/list', async (req, res) => {
// node 实现分页功能
// 1.获取前端传递过来的参数
const {
currentPage,
pageSize
} = req.query;
let n = (currentPage - 1) * pageSize;
let m = pageSize;
const sqlStr = `select * from finishProduct ORDER BY createTime DESC limit ${n},${m}`;
// 分页列表数据
await conn.query(sqlStr, (err, result) => {
// 获取总条数
const sqlStrCount = `select count(*) as count from finishProduct`;
const needToTransform = ['bindProps', 'bindPropsId', 'propsTable']
needToTransform.forEach(item => {
result.forEach((item2, index) => {
if(item2[item].length) {
item2[item] = JSON.parse(item2[item])
}
})
})
conn.query(sqlStrCount, (err, resultCount) => {
if (err) {
res.json({
"code": 1,
"message": "获取成品列表失败!",
})
}
res.json({
"code": 0,
"message": "获取成品列表成功!",
"data": result,
"total": resultCount[0].count
})
})
})
})
:::info
其中是对post请求中数组、对象字段进行转义
:::
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果