简体   繁体   English

来自API的2个并发请求数据混合在一起

[英]2 concurrent requests data from API were mixed up

I was using Nodejs as the backend of my app's API, but I realized that when there are 2 different users keep on requesting on the same method, the data return from MySQL requests might mixed up sometimes, here is my code: 我当时使用Nodejs作为应用程序API的后端,但是我意识到,当有2个不同的用户继续请求相同的方法时,有时MySQL请求返回的数据可能会混杂在一起,这是我的代码:

router.get('/v1/getList', function(req, res) {
    model.getList(loginUser, function(groups){
        if(!groups.length){
            res.json({data: '', success: false, message: 'No record found.'});
        } else{
            console.log("User:"+loginUser+", Length:"+groups.length);
            res.json({data: groups, success: true, message: ''});                    
        }
    });
});

loginUser is the user ID. loginUser是用户标识。 In normal condition the terminal output will be like below, which User 1 have 2 items and User 2 have 3 items: 正常情况下,终端输出如下所示,用户1有2个项目,用户2有3个项目:

User:1, Length:2
User:2, Length:3
User:1, Length:2
User:2, Length:3
and so on...

But once I keep refreshing the screen and the terminal might return: 但是一旦我不断刷新屏幕,终端可能会返回:

User:1, Length:2
User:2, Length:3
User:1, Length:3
User:2, Length:2

Which I suspect the data request by User 2 was being access by User 1 and vice versa, may I know how should I fix this? 我怀疑用户2正在访问用户2的数据请求,反之亦然,请问该如何解决?

You cannot use global variables to store loginUser from middleware. 您不能使用全局变量来存储中间件中的loginUser There can be multiple requests in flight at the same time. 一次可能有多个请求在飞行中。 Uisng a global like this mixes the data from multiple requests. 这样使用全局变量可以混合来自多个请求的数据。

The usual way to solve this issue is to store your data in the request object itself from your middleware. 解决此问题的常用方法是将数据存储在中间件的request对象本身中。 You can then access that property on the request object from your actual request handler. 然后,您可以从实际的请求处理程序访问request对象上的该属性。 Since the request object is unique to this specific request, there is no cross coupling of data between requests from different users. 由于请求对象对于此特定请求是唯一的,因此在来自不同用户的请求之间没有数据的交叉耦合。

Your request handler becomes this (using req.loginUser ): 您的请求处理程序将变成这个(使用req.loginUser ):

router.get('/v1/getList', function(req, res) {
    model.getList(req.loginUser, function(groups){
        if(!groups.length){
            res.json({data: '', success: false, message: 'No record found.'});
        } else{
            console.log("User:"+loginUser+", Length:"+groups.length);
            res.json({data: groups, success: true, message: ''});                    
        }
    });
});

And, you have to modify your middleware to set req.loginUser rather than the global variable. 并且,您必须修改中间件以设置req.loginUser而不是全局变量。

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

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