我正在使用Sqlite3编写节点应用程序的REST API。该应用程序将具有帐户,并且用户应该能够创建和更新一个帐户。我创建和提取帐户的代码按预期工作,但是我的更新函数抛出错误:“ TypeError:回调不是函数”
后端分为两个文件; db.js –我在其中设置数据库并为get / post / put / delete创建基本函数,而app.js –我在db中调用该函数并执行验证检查。
Project / rbrneck / rbrneck-backend / db.js:124 回调([],updatedAccount) ^
TypeError:回调不是函数 在Statement.db.run
代码:
//in db.js
exports.updateAccountById = (id, updatedAccount, callback) => {
const query = 'UPDATE accounts SET username = ?, password = ? WHERE id = ?'
const values = [
id,
updatedAccount.username,
updatedAccount.password
]
db.run(query, values, (error) => {
if(error) {
if(error.message == "SQLITE_CONSTRAINT: UNIQUE constraint failed: accounts.username") { //username taken
callback(['usernameTaken'])
} else {
callback(['databaseError'])
}
} else {
//const accountUpdated = (this.changes == 1)
callback([], updatedAccount) //HERE IS THE CALLBACK THE ERROR IS REFERRING TO
}
})
}
// in app.js:
app.put('/accounts/:id', (req, res, next) => {
const id = req.params.id
const updatedAccount = req.body
//errors and validation
//type of input
if(typeof(updatedAccount.username) !== 'string' && typeof(updatedAccount.password) !== 'string') {
res.status(422).json({
message: 'Unprocessable Entry'
}).end()
return
}
//does the account exist?
db.getAccountById(id, (errors, oldAccount) => {
if(errors.length > 0) {
res.status(500).json({
message: 'Internal Server Error'
}).end()
return
} else if (!oldAccount) {
res.status(404).end()
return
}
})
//validation:
const validationErrors = []
if(updatedAccount.username.length < USERNAME_MIN_LENGTH) {
validationErrors.push('Username too short')
} else if (updatedAccount.username.length > USERNAME_MAX_LENGTH) {
validationErrors.push('Username too long')
}
if(updatedAccount.password.length < PASSWORD_MIN_LENGTH) {
validationErrors.push('Password too short')
} else if (updatedAccount.password.length > PASSWORD_MAX_LENGTH) {
validationErrors.push('Password too long')
}
if(validationErrors.length > 0) {
res.status(400).json(validationErrors).end()
return
}
db.updateAccountById(updatedAccount, (errors, userId) => {
if(errors.length == 0) {
res.setHeader('Location', '/accounts/' + userId)
res.status(201).end()
} else if (errors.includes('usernameTaken')) {
res.status(400).json(errors).end()
} else {
res.status(500).end()
}
})
})