首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >快车比赛条件

快车比赛条件
EN

Stack Overflow用户
提问于 2018-12-01 03:18:01
回答 1查看 109关注 0票数 1

我正在开发一个角/节点/Express/Psql应用程序。对于该应用程序的部分内容,我得到了一些请求,用于Express检索用户配置文件。我有一个名为profile-pics的文件夹,它包含用户的图片,如果用户图片还不存在,它将从数据库中检索它并将其插入文件夹并返回图片。

GET url请求的当前设置方式是这样的调用:

代码语言:javascript
复制
user/profile-pic?username=bar123456

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

因此,例如,将运行两个GET请求

代码语言:javascript
复制
user/profile-pic?username=foo123456
user/profile-pic?username=bar123456

然而,这两张照片都将是bar123456图片。

我已经尝试过通过编写

代码语言:javascript
复制
console.log('Sending back picture ' + profilePicPath). 

当我这样做的时候,我会

代码语言:javascript
复制
'Sending back picture bar123456'
'Sending back picture bar123456'

这是返回图片的特快路线。我已经把数据库调用作为两个配置文件图片

代码语言:javascript
复制
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);
                }
            });
        }
    })
});

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-01 07:30:25

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

代码语言:javascript
复制
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()或自己发送响应。

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53567476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档