简体   繁体   English

我的 nodejs api 混合了客户端同时请求的 api 请求的代码

[英]My nodejs api mixes the codes of simultaneous api requests by clients

I have a nodejs server file which has an api as shown below to update the profile pictures.我有一个 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);
}
})

The VerifyAPIKey function is given below下面给出了 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);
}

The userdata is in a format as shown below用户数据的格式如下所示

{
   Id: 'FjWs0GZ4MkE_GCmKAAAD',
   Ip: '::1',
   API_KEY: '590c3789-e807-431b-bfdb-e20b6649e553',
   HOST: undefined,
   IsAuthenticated: false
}

The problem is the current code causes the response data from cloudinary to mix up between simultaneous requests.问题是当前代码导致来自 cloudinary 的响应数据在同时请求之间混淆。 I have tested it with two simultaneous requests.我已经用两个同时请求对其进行了测试。 Out of the two cloudinary responses whichever comes first is sent back as response to the user who invoked the api later than the two.在两个云响应中,以先到者为准,将作为响应发回给比两者晚调用 api 的用户。 And the user who invoked the api first get's an error saying cannot set headers after they are sent.调用 api 的用户首先得到一个错误,即在发送后无法设置标头。

I have tried searching for solution but haven't found any.我已经尝试寻找解决方案,但没有找到任何解决方案。 Can someone please help?有人可以帮忙吗?

How does data got initiated? data是如何启动的? data does not seem to be thread-safe and defined outside your async flow.数据似乎不是线程安全的,并且在您的异步流之外定义。 You may want to start from there and make sure data is thread-safe.您可能希望从那里开始并确保data是线程安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM