Express - 使用bcrypt异步提交到DB

时间:2018-04-25 04:23:20

标签: javascript postgresql

我在交易中运行以下代码:

app.post('/register', (req, res) => {
    const { email, name, password } = req.body;
    //insert syntax
    //When sending back response on an error from a server never send information back as error, instead send just a message
    dbConnection.transaction((trx) => {
        return trx.insert({
            name: name,
            emailaddress: email,
            createddt: new Date()
        }).into('users')
        .returning('emailaddress')
        .then((response) => {
            bcrypt.hash(password, saltRounds, function(err, hash) {
            console.log(response);
            dbConnection('login').insert({
            emailaddress: response,
            password: hash
            })
        })
        .catch(err => res.status(400).json(err))
    })
    })
})

我收到以下错误:

Unhandled rejection Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:491:11)
    at ServerResponse.setHeader (_http_outgoing.js:498:3)
    at ServerResponse.header (C:\Practice\React\sign-in-api\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\Practice\React\sign-in-api\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Practice\React\sign-in-api\node_modules\express\lib\response.js:267:15)
    at dbConnection.transaction.then.catch.err (C:\Practice\React\sign-in-api\server.js:67:32)
    at tryCatcher (C:\Practice\React\sign-in-api\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (C:\Practice\React\sign-in-api\node_modules\bluebird\js\release\promise.js:512:31)
    at Promise._settlePromise (C:\Practice\React\sign-in-api\node_modules\bluebird\js\release\promise.js:569:18)
    at Promise._settlePromise0 (C:\Practice\React\sign-in-api\node_modules\bluebird\js\release\promise.js:614:10)
    at Promise._settlePromises (C:\Practice\React\sign-in-api\node_modules\bluebird\js\release\promise.js:689:18)
    at Async._drainQueue (C:\Practice\React\sign-in-api\node_modules\bluebird\js\release\async.js:133:16)
    at Async._drainQueues (C:\Practice\React\sign-in-api\node_modules\bluebird\js\release\async.js:143:10)
    at Immediate.Async.drainQueues (C:\Practice\React\sign-in-api\node_modules\bluebird\js\release\async.js:17:14)
    at runCallback (timers.js:794:20)
    at tryOnImmediate (timers.js:752:5)

几个问题:

  1. 保存到DB时进行异步调用是个好主意吗?在这种情况下,bcrypt是异步调用。
  2. 有没有更好的方法来写下面的内容?
  3. 感谢任何回复。

0 个答案:

没有答案