express.js UnhandledPromiseRejectionWarning:错误:插入“表”

问题描述

node.js服务器代码

virtual

React.js前端代码

const uploadAction = (req,res,db) => {
    const { 
        name,address,phone,email,password,photo,accesses,verified
    } = req.body;

        if (!name || !address || !phone || !email || !password || !photo || !accesses) {
            return res.status(400).json('incorrect form submission');
        }
    
        const hash = bcrypt.hashSync(password);

        db.transaction(trx => {
        trx.insert({
            name:name,address:address,phone: phone,email: email,password: hash,photo: photo,permissions: accesses,verified: verified.toString()
        })
        .into('action')
        .then(site => {
            return res.json({"code":200,"id": site[0]});
        })
        .then(trx.commit)
        .catch(trx.rollback)
        })
        // .catch(err => res.status(400).json('unable to fetch'))
    
    }

错误

    submitForm = () => {
    const { accesses,name,confirm_password,check } = this.state;

    let url = FormatUrl(`/actions`);
    fetch(url,{
      method: 'POST',headers:{
          'Accept': 'application/json','Content-Type': 'application/json'
      },body: JSON.stringify({
          accesses: password,accesses:accesses,name: name,address: address,password: password,verified: check
      })
      })
      .then(res => res.json())
      .then(res => {
        if(res.code === 200){
          Toast.notification({ description: 'login success',type: 'success' });
        } else {
          Toast.notification({ description: 'Failed',type: 'error' });
        }
      }).catch(err => {
        Toast.notification({ description: 'Failed',type: 'error' });
      })
  }

在这里,我尝试使用express.js将一些数据插入Postgres数据库。我正在使用knex作为postgres客户端 从前端我正在发送所有数据。

但是,我遇到了以上错误。 以前的工作是相同的,但是无法理解错误,这里发生了什么 请看看

解决方法

如果permissions是一个jsonb字段,则在插入时应该执行JSON.stringify(accesses)

此外,由于postgres会对单个查询进行隐式事务,因此您无需为单次插入进行显式事务。

编写该事务的更好方法是:

db.transaction(trx => {
  // returning promise / thenable (which will be resolved to a promise) 
  // from transaction handler tells knex to implicitly commit if the promise
  // resolves fine or rollback if it rejects. 
  return trx('action').insert({
            name:name,address:address,phone: phone,email: email,password: hash,photo: photo,permissions: accesses,verified: verified.toString()
        });
})
.then(site => {
  // transaction was implicitly committed by knex with success
  res.json({"code":200,"id": site[0]});
})
.catch(err => {
  // transaction was implicitly rolled back by knex
  res.status(400).json('unable to fetch');
})

尽管我不知道那个未处理的承诺错误会在哪里出现。代码不清楚。