2 concurrent requests data from API were mixed up

2020-07-27 15:46发布

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:

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. In normal condition the terminal output will be like below, which User 1 have 2 items and User 2 have 3 items:

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?

1条回答
SAY GOODBYE
2楼-- · 2020-07-27 16:43

You cannot use global variables to store loginUser from middleware. 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. You can then access that property on the request object from your actual request handler. 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):

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.

查看更多
登录 后发表回答