代码之家  ›  专栏  ›  技术社区  ›  Braden Brown

GET期间的快速比赛状态

  •  1
  • Braden Brown  · 技术社区  · 6 年前

    我正在开发一个angular/node/express/psql应用程序。对于应用程序的一部分,我有一些请求将用于Express以检索用户配置文件。我有一个名为profile pics的文件夹,其中包含用户的图片,如果用户的图片还不存在,它将从数据库中检索该图片,并将其插入到文件夹中,然后返回图片。

    当前设置get url请求的方式是通过如下调用:

    user/profile-pic?username=bar123456
    

    它按快速路线,有些呼叫将返回相同的配置文件图片,即使请求了两个不同的配置文件图片。

    例如,将运行两个GET请求

    user/profile-pic?username=foo123456
    user/profile-pic?username=bar123456
    

    但是,这两张图片都是bar123456图片。

    我试着通过写作来调试它

    console.log('Sending back picture ' + profilePicPath). 
    

    当我这样做的时候,我会

    'Sending back picture bar123456'
    'Sending back picture bar123456'
    

    这是特快专递送回照片的路线。我打了数据库电话,因为已经有两张个人资料图片了

    userRouter.get('/user/profile-pic', function (req, res) {
        let userName = req.query.username;
        fileName = './profile-pics/' + userName + '.jpg';
        userProfilePic = userName + '.jpg';
    
        fs.exists(fileName, function (exists) {
            if (exists) {            
                console.log('Sending back picture ' + userProfilePic);
                res.status(200).contentType('image/png').sendFile(userProfilePic, {
                    root: path.join(__dirname, '../profile-pics/')
                }, function (err) {
                    if (err) {
                        console.log(err);
                    }
                });
            }
        })
    });
    

    我还尝试将字符串切片以创建一个新副本,因为我认为它可能只是复制了一个引用,而该引用已被更改。然而,这也不起作用。

    1 回复  |  直到 6 年前
        1
  •  2
  •   jfriend00    6 年前

    你需要正确申报 fileName userProfilePic 变量作为局部变量。当您不将它们声明为本地时,它们将成为隐式全局变量,并在不同的请求之间“共享”,这很容易导致争用条件,因为一个请求处理程序会覆盖另一个请求处理程序正在使用的值。更改为:

    userRouter.get('/user/profile-pic', function (req, res) {
        let userName = req.query.username;
        let fileName = './profile-pics/' + userName + '.jpg';
        let userProfilePic = userName + '.jpg';
    
        fs.exists(fileName, function (exists) {
            if (exists) {            
                console.log('Sending back picture ' + userProfilePic);
                res.status(200).contentType('image/png').sendFile(userProfilePic, {
                    root: path.join(__dirname, '../profile-pics/')
                }, function (err) {
                    if (err) {
                        console.log(err);
                    }
                });
            }
        })
    });
    

    另外,您还需要在所有代码路径中发送响应,例如文件不存在或错误处理程序中。通过路由处理程序的所有路径都应调用 next() 或者自己发送响应。

    仅供参考,通过linter运行代码和/或在严格模式下运行代码将使这些编程错误更加明显。

    推荐文章