如何解决Node.js快速连续PUT请求未正确执行
该应用是使用Express在Node.js中编写的。我也在使用MongoDB和Mongoose。
有一个PUT端点可以更新用户信息,例如用户的名字,年龄等以及他/她喜欢的汽车以及每辆汽车的价格。端点接收一个名为newProfileData的数组,如下所示。
select *
from your_table
where col like '%the%'
order by case when col = 'the' then 1 else 2 end,col
不幸的是,由于我从前端接收数据的方式,我必须提出单独的提取请求。如果仅添加一辆汽车并发送一个提取请求,则“ cars / add”端点工作正常,但如果添加多辆汽车,则数据会以某种方式在“ cars / add”端点中被覆盖,并且如果我开始向其中添加控制台日志调试时,通过添加一辆汽车而不是另一辆汽车,代码甚至以一种怪异的方式运行,但是如果我多次尝试代码,则它将更改要添加的汽车。请查看下面的“汽车/加油站”端点:
router.put(
"/",middleware.verifyToken,[check("newProfileData").not().isEmpty().trim().escape()],async function (req,res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json(errors.array());
}
try {
// update profile collection if the firstname has changed
// also update likedCars collection if the user adds new cars; doing this by sending a fetch post request to the /addCar endpoint
// if the liked car is Aston Martin then send a post request to add Aston Martin
fetch(process.env.APPLICATIONURL + "cars/add",{
method: "post",body: JSON.stringify(carData),headers: {
Authorization: "Bearer " + req.bearerToken,"Content-Type": "application/json",},})
.then((res) => res.json())
.then((dataObj) => {
})
.catch((err) => {
console.log(err);
return res.status(422).json("Could not update.");
});
// if the liked car is Ferrari send another fetch request
fetch(process.env.APPLICATIONURL + "cars/add",})
.then((res) => res.json())
.then((dataObj) => {
})
.catch((err) => {
console.log(err);
return res.status(422).json("Could not update.");
});
} catch (err) {
console.log(err);
return res.status(422).json(err);
}
}
);
}
当我发送两个或多个连续的提取时,会发生问题。大多数情况下,“ newRes.car = carResult;”会被忽略,并且我没有为第一次提取发送的第一辆汽车添加汽车钥匙到newRes中,但是从第二次提取中为第二辆汽车添加了汽车钥匙。
有人可以帮助我吗?谢谢。
解决方法
我设法找出问题所在...
这行代码
for (newRes of carData)
需要更改为
for (let newRes of carData)
否则newRes将存储为全局变量...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。