【发布时间】:2020-12-06 20:04:41
【问题描述】:
我有一个 nodejs 服务器文件,它有一个如下所示的 api 来更新个人资料图片。
app.post('/updateProfilePic', async(req, res) => {
try {
if (VerifyAPIKey(req.query.key)) {
let userdata = users.find(e => e.Id == req.query.socketId);
if (userdata) {
for (var a = 0; a < users.length; a++) {
const b = a;
if (users[a].IsAuthenticated) {
if (req.query.pub) {
cloudinary.uploader.destroy(req.query.pub, {resource_type: 'image'}, function(err, res) {
// console.log(err, res);
});
}
cloudinary.uploader.upload(req.files.profilePic.tempFilePath, {resource_type: 'image', folder: 'members', eager: [
{width: 25, height: 25, g: 'face', radius: "max", crop: 'fill', format: "png"},
{width: 50, height: 50, g: 'face', radius: "max", crop: 'fill', format: "png"},
{width: 100, height: 100, g: 'face', radius: "max", crop: 'fill', format: "png"},
{width: 250, height: 250, g: 'face', radius: "max", crop: 'fill', format: "png"},
{width: 500, height: 500, g: 'face', crop: 'fill'},
]}, function(err,response) {
if (err) {
console.log(err);
}
if (response) {
const logo = userModel.findOneAndUpdate({
_id: users[b]._id,
},{
PictureUrl: response
}, (err, result) => {
data.status = 200;
data.message = "Your Profile Picture has been updated!"
res.status(200).send(data);
})
}
});
}
}
} else {
data.status = 404;
data.message = "Invalid User!";
res.status(200).send(data);
}
} else {
res.json('Unauthorized request!');
}
} catch(err) {
res.status(400).send(err.message);
}
})
VerifyAPIKey 函数如下所示
function VerifyAPIKey(key) {
var a = users.find(e=> e.API_KEY == key);
console.log(a)
fs.appendFile('./data/apiRequests.txt', JSON.stringify(a) + "\r\n", function (err) {
if (err) throw err;
});
return Boolean(a);
}
用户数据格式如下图
{
Id: 'FjWs0GZ4MkE_GCmKAAAD',
Ip: '::1',
API_KEY: '590c3789-e807-431b-bfdb-e20b6649e553',
HOST: undefined,
IsAuthenticated: false
}
问题是当前代码导致来自 cloudinary 的响应数据在同时请求之间混淆。我已经用两个同时请求对其进行了测试。在两个云响应中,无论哪个先来,都会作为响应发回给晚于两者调用 api 的用户。而调用api的用户第一次get的时候会报错,说发送后不能设置headers。
我已尝试搜索解决方案,但没有找到任何解决方案。有人可以帮忙吗?
【问题讨论】:
标签: node.js api express mongoose cloudinary