我正在开发一个角/节点/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);
}
});
}
})
});我还尝试对字符串进行切片以创建一个新副本,因为我认为它可能只是在复制引用,并且引用被更改了。然而,这也不起作用。
发布于 2018-12-01 07:30:25
您需要正确地将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()或自己发送响应。
FYI,通过linter运行代码和/或在严格模式下运行代码将使这些编程错误更加明显。
https://stackoverflow.com/questions/53567476
复制相似问题