如何在node.js和mysql中的另一个插件中插入一个插件



我在这篇文章中执行了一个插入,我需要获得id才能在另一个插入中使用它。

router.post('/save_card', verifyToken, (req, res) => {
const page = req.body.page;
const container_card = req.body.container_card;

mysqlConnection.query('INSERT INTO pages (name_page) VALUES (?)', [page],
(err, results, fields) => {
if (err) throw err;

container_card.forEach(card => {
mysqlConnection.query('INSERT INTO cards (id_page, container_card) VALUES (?,?)', [results.insertId, card],
(err, rows, fields) => {
if (err) throw err;
res.json({
message: 'Card created successfully',
});
});
});
});
});

它工作,但它给我一个错误

C: \Users\lcardemi\Desktop\PROYECTO CARD 3.0\backend\node_modules\mysql\lib\protocol\Parser.js:437抛出错误;//重试非MySQL错误^错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头

步骤1。

执行提供[page]作为参数的INSERT INTO pages (name_page) VALUES (?)

步骤2。

执行提供[card, page]作为参数的INSERT INTO cards (id_page, container_card) SELECT id, ? FROM pages WHERE name_page = ?。仅当pages.name_page被定义为唯一时才适用。

或者执行提供[card]作为参数的INSERT INTO cards (id_page, container_card) VALUES (LAST_INSERT_ID(), ?)。但是必须在同一连接中执行此查询,并且必须保证在步骤1和步骤2之间没有执行任何查询,包括连接器发送的隐藏语句。

最新更新