![](/img/trans.png)
[英]NodeJS SQL Login Error (ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client)
[英]How to solve the sql errno: '1064' and ERR_HTTP_HEADERS_SENT error?
我有以下代碼,其中包含幾個 sql 查詢:
createNewOrder: (data,callBack) => {
pool.query(
`Insert into ordering (supplycontract) values (?)`,
[
data.supplierId
],
(error,results,fields) => {
if(error){
return callBack(error)
}
pool.query(
`select id from ordering order by id desc limit 1`,
[
data.articleId
],
(error,results1,fields) =>{
if(error){
return callBack(error)
}
let orderid = results1[0].id;
console.log(orderid);
pool.query(
`Insert into position (quantity,delivery,ordering,positioninorder,articlecontract) values(?,?,?,1,?)`,
[
data.quantity,
new Date(),
orderid,
data.articleId
],
(error,results3,fields) => {
if(error){
callBack(error)
}
//callBack(null,results3)
}
);
}
);
return callBack(null,results)
}
);
}
我嘗試了幾種技巧並改進了代碼,但不幸的是我收到以下錯誤:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
'position (quantity,delivery,ordering,positioninorder,articlecontract) values(54,' at line 14
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'position (quantity,delivery,ordering,positioninorder,articlecontract) values(54,' at line 1",
sqlState: '42000',
index: 0,
sql: "Insert into position (quantity,delivery,ordering,positioninorder,articlecontract) values(54,'2021-07-11 19:18:39.334',16,1,5)"
}
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:518:11)
code: 'ERR_HTTP_HEADERS_SENT'
您的代碼有多個問題
return callBack(null,results)
應該在第三個查詢的回調中。callBack(error)
應該有像return callBack(error)
這樣的return callBack(error)
語句。position
作為表名。 如果您的 SQL 查詢包含保留關鍵字,您可以使用反引號"``"
來轉義保留關鍵字。createNewOrder: (data, callBack) => {
pool.query(`Insert into ordering (supplycontract) values (?)`, [data.supplierId], (error, results, fields) => {
if (error) {
return callBack(error)
}
pool.query(`select id from ordering order by id desc limit 1`, [data.articleId], (error, results1, fields) => {
if (error) {
return callBack(error)
}
let orderid = results1[0].id;
console.log(orderid);
pool.query("Insert into `position` (quantity,delivery,ordering,positioninorder,articlecontract) values(?,?,?,1,?)", [data.quantity, new Date(), orderid, data.articleId], (error, results3, fields) => {
if (error) {
return callBack(error)
}
return callBack(null, results)
});
});
});
}
一些注意事項
Cannot set headers after they are sent
發送響應,簡而言之,如果您在一個請求周期中兩次調用res.json()
或res.status().json()
,您將得到上述錯誤。function myController(req, res) {
res.json({ status: "success" });
res.json({ status: "success" }); // this will throw the error defined above
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.