我的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是线程安全的。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...