当前位置: 首页 > 知识库问答 >
问题:

前端 - 新增接口明明传值了却没有保存到数据?更新接口却能保存进去,什么原因?

小牛23064
2024-06-14

新增接口传值
图片.png
获取详情
图片.png
更新接口传值
图片.png
获取详情
图片.png
数据图表结构
图片.png
图片.png

后端代码

/*产品报价模块cherry 2024.4 */const express = require('express');const router = express.Router();const expressJwt = require('express-jwt');const { runLog } = require('../utils/logger');const query = require('../utils/db');// 新增报价router.post('/add', expressJwt({    secret: 'SHIBANGTUSHUGUAN',    algorithms: ['HS256'],    getToken: (req) => {        return req.headers.token || null    }}), async function (req, res) {    addOffer(req.body).then(() => {        res.json({ errMsg: '新增产品报价成功', code: 20000 });    }).catch((err) => {        runLog.error(err)        res.json({ errMsg: '新增产品报价失败', code: 50000, err: err.message });    })});// 获取单个报价详情router.get('/detail', expressJwt({    secret: 'SHIBANGTUSHUGUAN',    algorithms: ['HS256'],    getToken: (req) => {        return req.headers.token || null    }}), async function (req, res) {    let result = await getOfferById(req.query.id)    await res.json({ errMsg: 'ok', code: 20000, data: { detail: result } });});// 获取报价列表router.get('/list', expressJwt({    secret: 'SHIBANGTUSHUGUAN',    algorithms: ['HS256'],    getToken: (req) => {        return req.headers.token || null    }}), async function (req, res) {    let pageSize = Number(req.query.pageSize)    let page = Number(req.query.page)    let type = req.query.type    if (!pageSize || !page) {        res.json({ errMsg: '请传入合适的分页信息', code: 40300, err: null });        return    }    if (!type) {        res.json({ errMsg: '请传入上级目录分类信息', code: 40300, err: null });        return    }    delete req.query.pageSize    delete req.query.page    delete req.query.type    const { sqlStr, sqlParams } = formatParams(req.query, req.data.role, type)    let count = await getCount(sqlStr, sqlParams)    let result = await getOfferList(sqlStr, sqlParams, page, pageSize)    await res.json({ errMsg: 'ok', code: 20000, data: { list: result, total: count[0].total } });});// 修改报价router.post('/update/:id', expressJwt({    secret: 'SHIBANGTUSHUGUAN',    algorithms: ['HS256'],    getToken: (req) => {        return req.headers.token || null    }}), function (req, res) {    updateOffer(req.body, req.params.id).then(() => {        res.json({ errMsg: 'ok', code: 20000 });    }).catch((err) => {        res.json({ errMsg: '修改报价信息失败', code: 50000, err: err.message });    })});// 删除报价router.get('/delete/:id', expressJwt({    secret: 'SHIBANGTUSHUGUAN',    algorithms: ['HS256'],    getToken: (req) => {        return req.headers.token || null    }}), function (req, res) {    deleteOffer(req.params.id).then(() => {        res.json({ errMsg: 'ok', code: 20000 });    }).catch((err) => {        res.json({ errMsg: '删除报价信息失败', code: 50000, err: err.message });    })});// 新增报价function addOffer(data) {    let sql = 'insert into product_offer (code,name,version_num,power,price_type,currency,first_price,second_price,third_price,fourth_price,remark,pictureList,type,photo_num,create_time,update_time) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);'    return new Promise((resolve, reject) => {        query(sql, [data.code, data.name, data.version_num, data.power, data.price_type, data.currency, Number(data.first_price), Number(data.second_price), Number(data.third_price), Number(data.fourth_price), data.remark, data.pictureList, data.type, data.photo_num, new Date(), new Date()], (err) => {            if (err) {                runLog.error('addOffer出错' + err)                reject(err)            } else {                runLog.info('addOffer成功' + data)                resolve()            }        })    })}// 获取单个报价详情function getOfferById(id) {    let sql = `select * from product_offer where id = ?;`    return new Promise(((resolve, reject) => {        query(sql, [id], (err, rows, fields) => {            if (err) {                runLog.error('getOfferById出错' + err)                reject(err)            } else {                runLog.info('getOfferById成功读取')                resolve(rows)            }        })    }))}// 处理查询参数function formatParams(data, role, type) {    let str = ''    let params = []    if (data.length < 1) {        return { str, params }    }    Object.keys(data).forEach(key => {        if (!data[key]) return        if (key !== 'price') {            str += `${key} LIKE  ? and `            params.push(`%${data[key]}%`)        } else {            let name = 'first_price'            switch (role) {                case 2: name = 'second_price'                    break                case 3: name = 'third_price'                    break                case 4: name = 'fourth_price'                    break            }            let temp = data.price.split(',')            str += `${name} >=  ? and `            str += `${name} <=  ? and `            params.push(Number(temp[0]))            params.push(Number(temp[1]))        }    })    if (type) {        let typeArr = type.split(',')        let inArr = []        typeArr.forEach(item => {            inArr.push("?")            params.push(item)        })        str += `type in(${inArr.toString()})`    } else {        str = str.slice(0, -4)    }    return { sqlStr: str, sqlParams: params }}// 获取报价列表function getOfferList(sqlStr, sqlParams, page, pageSize) {    let start = (page - 1) * pageSize    let sql = `select * from product_offer `    if (sqlStr) {        sql += `where ${sqlStr} limit ?, ? ;`    } else {        sql += `limit ?, ? ;`    }    return new Promise(((resolve, reject) => {        query(sql, [...sqlParams, start, pageSize], (err, rows, fields) => {            if (err) {                runLog.error('getOfferList出错' + err)                reject(err)            } else {                runLog.info('getOfferList成功读取')                resolve(rows)            }        })    }))}// 获取用户列表总数function getCount(sqlStr, sqlParams) {    let sql = `select count(id) as total from product_offer `    if (sqlStr) {        sql += `where ${sqlStr}`    }    return new Promise(((resolve, reject) => {        query(sql, sqlParams, (err, rows, fields) => {            if (err) {                runLog.error('getCount出错' + err)                reject(err)            } else {                runLog.info('getCount成功读取')                resolve(rows)            }        })    }))}// 修改报价function updateOffer(data, id) {    let params = []    let str = ''    Object.keys(data).forEach(key => {        if (key !== 'id' && key !== 'creat_time' && key !== 'update_time') {            str += `${key} = ?,`            params.push(data[key])        }    })    str += `update_time = ?,`    params.push(new Date())    params.push(id)    let sql = `update product_offer set ${str.slice(0, -1)} where id = ?;`    return new Promise((resolve, reject) => {        query(sql, params, (err) => {            if (err) {                runLog.error('updateOffer出错' + err)                reject(err)            } else {                runLog.info('updateOffer成功')                resolve()            }        })    })}// 删除报价function deleteOffer(id) {    let sql = 'delete from product_offer where id = ?;'    return new Promise((resolve, reject) => {        query(sql, [id], (err) => {            if (err) {                runLog.error('deleteOffer出错' + err)                reject(err)            } else {                runLog.info('deleteOffer成功')                resolve()            }        })    })}module.exports = router;

共有2个答案

国高杰
2024-06-14

新增的话是自增主键吗?你确定第一张图新增进数据库的ID是160,然后再查出来没有pictureList这一列数据的吗?

钮安歌
2024-06-14

addOffer 中 输出下 data 和 data.pictureList

 类似资料:
  • 基本信息 Path: /api/interface/save Method: POST 接口描述: 请求参数 Headers 参数名称 参数值 是否必须 示例 备注 Content-Type application/json 是 Body { "token": "...", "req_query": [], "req_headers": [ { "name": "C

  • 假设要对下面这个接口提供开放能力。 @RestController public class StoryDemoController { @RequestMapping("/story/get") public StoryResult getStory() { StoryResult result = new StoryResult(); resu

  • 基本信息 Path: /api/interface/add Method: POST 接口描述: 请求参数 Headers 参数名称 参数值 是否必须 示例 备注 Content-Type application/json 是 Body { "token": "xxx", "req_query": [], "req_headers": [ { "name": "Co

  • 为什么我的值不能进入数据库? 如果需要更多的代码,请告诉我。 警告: 查询连接中的异常。php第713行:SQLSTATE[23000]:完整性约束冲突:1048列“name”不能为空(SQL:insert-into(,,,,)值(,,2016-06-19 21:44:05,2016-06-19 21:44:05)) 控制器: HTML页面:

  • 我有一个Spring应用程序,其中Domain Object标识符不是由数据库分配的,而是由应用程序生成的。标识符是在BeforeSave回调期间生成并添加到Domain Object中的。保存域对象(插入)后,当尝试保存具有相同标识符的域对象(更新)时,我收到以下错误 原因:组织。springframework。道。Incorrectupdatesemanticdataaccessexcepti