如何解决我的nodejs api混合了客户端同时api请求的代码
我有一个nodejs服务器文件,该文件具有如下所示的api,用于更新个人资料图片。
app.post('/updateProfilePic',async(req,res) => {
try {
if (VerifyAPIKey(req.query.key)) {
let userdata = users.find(e => e.Id == req.query.socketId);
if (userdata) {
for (var a = 0; a < users.length; a++) {
const b = a;
if (users[a].IsAuthenticated) {
if (req.query.pub) {
cloudinary.uploader.destroy(req.query.pub,{resource_type: 'image'},function(err,res) {
// console.log(err,res);
});
}
cloudinary.uploader.upload(req.files.profilePic.tempFilePath,{resource_type: 'image',folder: 'members',eager: [
{width: 25,height: 25,g: 'face',radius: "max",crop: 'fill',format: "png"},{width: 50,height: 50,{width: 100,height: 100,{width: 250,height: 250,{width: 500,height: 500,crop: 'fill'},]},response) {
if (err) {
console.log(err);
}
if (response) {
const logo = userModel.findOneAndUpdate({
_id: users[b]._id,},{
PictureUrl: response
},(err,result) => {
data.status = 200;
data.message = "Your Profile Picture has been updated!"
res.status(200).send(data);
})
}
});
}
}
} else {
data.status = 404;
data.message = "Invalid User!";
res.status(200).send(data);
}
} else {
res.json('Unauthorized request!');
}
} catch(err) {
res.status(400).send(err.message);
}
})
VerifyAPIKey函数在下面给出
function VerifyAPIKey(key) {
var a = users.find(e=> e.API_KEY == key);
console.log(a)
fs.appendFile('./data/apiRequests.txt',JSON.stringify(a) + "\r\n",function (err) {
if (err) throw err;
});
return Boolean(a);
}
用户数据的格式如下所示
{
Id: 'FjWs0GZ4MkE_GCmKAAAD',Ip: '::1',API_KEY: '590c3789-e807-431b-bfdb-e20b6649e553',HOST: undefined,IsAuthenticated: false
}
问题是当前代码导致来自cloudinary的响应数据在并发请求之间混合。我已经同时测试了两个请求。在这两个云响应中,以先到者为准,将其作为响应发送回给比这两个事件晚调用api的用户。而且首先调用api的用户会收到一条错误消息,说发送标头后无法设置标头。
我尝试搜索解决方案,但未找到任何解决方案。有人可以帮忙吗?
解决方法
data
是如何启动的?数据似乎不是线程安全的,并且在异步流之外定义。您可能要从那里开始,并确保data
是线程安全的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。