使用template literals node js调用mysql列



我试图使用模板文本从node-js文件中的mysql调用一个字段,但无法获得值。请查看下面的post.controller.js文件,其中显示消息:Post ${body.post_id} was successfully created,其中post_id是我的mysql数据库中的一个字段。

//以下代码位于post.service.js文件中

const pool = require("../../config/database");
module.exports = {
//Create new post
createPost: (data, callBack) =>{
pool.query(
`insert into posts(userhandle, post_body)
values(?,?)`,
[
data.userhandle,
data.post_body
],
(error, results, fields) =>{
if(error){
return callBack(error);
}
return callBack(null, results);
}
);
}
}

//以下代码位于post.controller.js文件中

const {
createPost,
} = require("./post.service");

module.exports = {
//Controller for creating new post
createPost: (req, res) =>{
const body = req.body;
createPost(body, (err, results) => {
if(err){
console.log(err);
return res.status(500).json({
success:0,
message:"Error. Unable to create post"
});
}
return res.status(200).json({
success: 1,
message: `Post ${body.post_id} was successfully created`,
data: results
});
});
}
}

我猜post_id是一个PK自动递增的,如果是这样的话,请尝试results.post_id,因为这是一个从回调中返回的对象。如果这不起作用,请执行console.log(results)并查看post_id是否在其中。

最新更新