【发布时间】:2020-01-16 06:18:51
【问题描述】:
您好,我正在尝试将一条记录从一个帖子(使用邮递员进行测试)中插入一个 REST API 的 MySQL 数据库。我不断收到服务器错误。这是我的代码(使用 async 和 await 并期望得到回报)。这是路由器:
* Creates a new user.
*/
router.post('/', async (req, res, next) => {
const options = {
body: req.body
};
try {
const result = await user.createUser(options);
res.status(result.status || 200).send(result.data);
} catch (err) {
next(err);
}
});
这里是服务(更新 - 仍然错误):
sql = "INSERT INTO users (AccountHolderUserID, isSubUser, parentUsersID, appBrand, accessLevel, accessToken, tempPassword, email, firstName, lastName) VALUES ?";
values = [
[options.body.AccountHolderUserID, options.body.isSubUser, options.body.parentUsersID, options.body.appBrand, options.body.accessLevel, options.body.accessToken, options.body.tempPassword, options.body.email, options.body.firstName, options.body.lastName]
];
console.log(values);
pool.query(sql, [values], function (error, result, fields) {
if (error) {
reject(new ServerError({
status: 500, // Or another error code.
error: 'Server Error' // Or another error message.;
}));
return
}
resolve({
status: 200,
data: result
});
})
});
}
我在 pool.query 之前添加了一个控制台日志,这是我尝试发布时的响应。数据正在从表单到查询,但是得到一个无法将对象转换为原始值的错误???
App listening on port 8082!
[
[
'1234, ',
'true,',
'1,',
'1,',
'1,',
'1312,',
'1234,',
'notifications@answeringmobile.com,',
'Nancy,',
'Flannagan'
]
]
TypeError: Cannot convert object to primitive value
如果有人知道我做错了什么,请告诉我。谢谢!
【问题讨论】:
-
请在 pool.query 之前打印用户对象的 console.log 并验证对象每个元素的类型。
-
从插入查询中删除
set。set用于update record。这是示例代码w3schools.com/nodejs/nodejs_mysql_insert.asp -
谢谢,我尝试并更新了上面的代码,但同样的错误。控制台日志正在显示数据。