NodeJS nextjsapi是否荣誉承诺?

hc8w905p  于 2022-12-12  发布在  Node.js
关注(0)|答案(1)|浏览(106)

我希望你是好的,我有一个问题,我正在学习NEXTJS和工作与它的API,结果是,当我点击非常快的承诺得到bug.或类似的东西,我离开了测试在这个短视频的30秒和代码的演示,我希望有人能帮助我,非常感谢.
https://www.youtube.com/embed/K0JTMxpFLQs

  • -------------代码------------
    我的请求AXIOS:
axios.post("/api/reaction", data).then((response) => { return response.data }).then(response => {
        if (response.react) {
            setNew[key].youLike = true
            setNew[key].likes = response.likes
            setting(setNew => [...setNew])
        } else {
            setNew[key].youLike = false
            setNew[key].likes = response.likes
            setting(setNew => [...setNew])
        }
    })

我的后端:

export default async function react(req, res) {
let msg, msg_type, react, likes
let { type, id } = req.body
let myId = mySession(req)

if (myId && type && id) {
    react = await youLike(myId, id, type)

    console.log(react)
    if (react) {
        await executeQuery({ query: `DELETE FROM cms_likes WHERE owner_id='${myId}' and type='${type}' and post_id='${id}'` })
        await executeQuery({ query: `UPDATE cms_posts SET likes=likes-1 WHERE id='${id}' ` })
        react = false
    } else {
        await executeQuery({ query: `INSERT INTO cms_likes (owner_id,type,post_id,time) VALUES ('${myId}','${type}','${id}','${timeNow("s")}') ` })
        await executeQuery({ query: `UPDATE cms_posts SET likes=likes+1 WHERE id='${id}' ` })
        react = true
    }

    likes = await executeQuery({ query: `SELECT likes FROM cms_posts WHERE id='${id}'` })
} else {
    msg_type = "error"
    msg = "!Opps error al enviar tu peticion"
}

res.send({ msg, msg_type, react, likes: likes[0]?.likes })

}
通过多次点击该按钮,“赞”按钮并没有承诺检查它是否存在或不太好,而是加倍了“赞”。
存在慢速CLIC
slowclick
回应:
0未找到1是有0未找到1是有0未找到
快速点击响应:
response
2重复2重复0未找到1是有0未找到1是有0未找到3重复
了解承诺如何运作良好,以便找到解决这个问题的方法,我的帖子将帮助那些可能有同样错误的人。
我的连接SQL和函数EXECUTEQUERY

const db = mysql({
config: {
    host: "localhost",
    database: "baalbcms",
    user: "root",
    password: ""
}

})

export default async function executeQuery({ query, values }) {
try {
    const results = await db.query(query, values)
    await db.end()
    return results
} catch (err) {
    return err;
}

}

vhmi4jdf

vhmi4jdf1#

为了使您的SQL更加健壮,您应该始终根据喜欢表来计算喜欢的实际数量;实际上,它们有可能不同步。
我还冒昧地使用values修复了您代码中的SQL注入漏洞。
如果在单个事务中运行查询,这会更好,但使用当前的dbthat you end after every query (which you shouldn't do)无法轻松完成。

if (react) {
  await executeQuery({
    query: "DELETE FROM cms_likes WHERE owner_id=? and type=? and post_id=?",
    values: [myId, type, id],
  });
} else {
  await executeQuery({
    query: "INSERT INTO cms_likes (owner_id,type,post_id,time) VALUES (?, ?, ?, ?)",
    values: [myId, type, id, timeNow("s")],
  });
}
await executeQuery({
  query: "UPDATE cms_posts SET likes=(SELECT COUNT(*) FROM cms_likes WHERE type=? and post_id=?) WHERE id=?",
  values: [type, id, id],
});
likes = await executeQuery({ query: `SELECT likes FROM cms_posts WHERE id=?`, values: [id] });

相关问题