Angular GET期间的快速竞争条件
我正在开发Angular/Node/Express/Psql应用程序。对于应用程序的一部分,我得到了要快速检索用户配置文件的请求。我有一个名为profile pics的文件夹,其中包含用户的图片,如果用户的图片还不存在,它将从数据库中检索并将其插入文件夹,然后返回图片 当前设置GET url请求的方式是通过如下调用:Angular GET期间的快速竞争条件,angular,express,Angular,Express,我正在开发Angular/Node/Express/Psql应用程序。对于应用程序的一部分,我得到了要快速检索用户配置文件的请求。我有一个名为profile pics的文件夹,其中包含用户的图片,如果用户的图片还不存在,它将从数据库中检索并将其插入文件夹,然后返回图片 当前设置GET url请求的方式是通过如下调用: user/profile-pic?username=bar123456 它点击了快速路线,即使请求了两张不同的个人资料图片,一些电话仍会返回相同的个人资料图片 例如,将运行两个G
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'
这是express中返回图片的路线。我取出了数据库电话,因为两张个人资料照片都已经存在
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);
}
});
}
})
});
我还尝试过对字符串进行切片以创建新副本,因为我认为它可能只是在复制引用,而引用被更改了。但是,这也不起作用。您需要正确地将
文件名
和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运行代码和/或在strict模式下运行代码将使这些编程错误更加明显