【问题标题】:express.js UnhandledPromiseRejectionWarning: error: insert into "table"express.js UnhandledPromiseRejectionWarning:错误:插入“表”
【发布时间】:2021-02-07 05:52:28
【问题描述】:

node.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'))
    
    }

React.js 前端代码:

    submitForm = () => {
    const { accesses, name, address, email, phone, password, confirm_password, photo, check } = this.state;

    let url = FormatUrl(`/actions`);
    fetch(url, {
      method: 'POST',
      headers:{
          'Accept': 'application/json',
          'Content-Type': 'application/json'
      },
      body: JSON.stringify({
          accesses: password,
          email: email,
          accesses:accesses,
          name: name,
          address: address,
          phone: phone,
          password: password,
          photo: photo,
          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' });
      })
  }

错误:

    (node:23763) UnhandledPromiseRejectionWarning: error: insert into "action" ("address", "email", "name", "password", "permissions", "phone", "photo", "verified") values ($1, $2, $3, $4, $5, $6, $7, $8) - malformed array literal: "{"sites":["create","update","view"],"isp":["create","update","view","delete"],"ipam":["view","delete"],"topology":null,"floor plan":null,"rack":["view"],"devices":null,"outage tracker":["create"],"guides":["create","update","view","delete"]}"
    at Parser.parseErrorMessage (/Users/soubhagyapradhan/Desktop/upwork/keyboo/backend/node_modules/pg-protocol/dist/parser.js:241:15)
    at Parser.handlePacket (/Users/soubhagyapradhan/Desktop/upwork/keyboo/backend/node_modules/pg-protocol/dist/parser.js:89:29)
    at Parser.parse (/Users/soubhagyapradhan/Desktop/upwork/keyboo/backend/node_modules/pg-protocol/dist/parser.js:41:38)
    at Socket.<anonymous> (/Users/soubhagyapradhan/Desktop/upwork/keyboo/backend/node_modules/pg-protocol/dist/index.js:8:42)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:302:12)
    at readableAddChunk (_stream_readable.js:278:9)
    at Socket.Readable.push (_stream_readable.js:217:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
    (Use `node --trace-warnings ...` to show where the warning was created)
    (node:23763) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
    (node:23763) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

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

但是,我遇到了错误。 之前的工作是相同的,但无法理解这里发生的错误 请看一下

【问题讨论】:

  • 您收到警告,因为您没有 catch 块。由于malformed array literal,您的代码引发错误(您不是catching) - 这意味着数组的格式或语法不正确(Read this

标签: node.js reactjs postgresql express knex.js


【解决方案1】:

如果 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');
})

虽然我不知道那个未处理的承诺错误来自哪里。从代码中看不清楚。

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 1970-01-01
    • 2018-02-23
    • 2021-11-17
    • 1970-01-01
    • 2019-11-02
    • 2021-08-30
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多