繁花不似錦
2023-06-09 10:53:04
執行組合查詢時出錯我正在使用 sequelize 和 mysql這是我的代碼:const makeAuthenticate = async (req, res) => { const newOtp = Math.floor(100000 + Math.random() * 900000); try { const {phone} = req.body; const [user, created] = await db.User.findOrCreate({ where: { phone: phone }, }) .then(e => { db.User.update({ otp: newOtp }, { where: { phone: phone }}) .then(f => res.status(200).json({ otp: newOtp })) .catch(err => res.status(500).json({error: err})) // Error comes from here ! }) .catch(err => res.status(500).json({error: err})) } catch (error) { return res.status(500).json({error: error.message}) }}這是我對代碼所做的事情:基本上,我在單個查詢中同時進行注冊和登錄,換句話說,首先使用 findOrCreate - 我找到用戶或者我將創建一個新用戶,然后我需要發送一次密碼(這是臨時的 6 位數字“)他們在流程中使用的電話號碼。所以,我正在將 otp 更新到我的用戶表,然后我需要添加調用以向用戶發送 SMS(我還沒有這樣做)所以現在處于 findOrCreate 階段并再次調用特定的更新用戶。通過這個我得到一個錯誤如下:UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
1 回答

烙印99
TA貢獻1829條經驗 獲得超13個贊
嘗試這樣的事情
const makeAuthenticate = async (req, res) => {
const newOtp = Math.floor(100000 + Math.random() * 900000)
const {phone} = req.body
try {
const [user, created] = await db.User.findOrCreate({
where: { phone: phone }
})
const updatedRes = await db.User.update({ otp: newOtp }, { where: { phone: phone }})
res.status(200).json({
otp: newOtp
})
} catch(e) {
res.status(500).json({error: err})
}
}
沒有必要嵌套承諾,.then()你可以只使用awaitsince Sequelizeuses 承諾。
您的代碼的主要問題是您.catch()在內部使用try catch并且他們都試圖在失敗時發送狀態。因此,很可能您的問題出在其他地方,但這是副作用,當您運行我的代碼時,您應該會看到真正的問題(如果存在)。
添加回答
舉報
0/150
提交
取消