[英]My nodejs api mixes the codes of simultaneous api requests by clients
我有一个 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, g: 'face', radius: "max", crop: 'fill', format: "png"},
{width: 100, height: 100, g: 'face', radius: "max", crop: 'fill', format: "png"},
{width: 250, height: 250, g: 'face', radius: "max", crop: 'fill', format: "png"},
{width: 500, height: 500, g: 'face', crop: 'fill'},
]}, function(err,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
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
是线程安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.