MySQL 数据库保存着用户图像,我想查询该图像并将其显示在导航栏上。这是我的导航栏组件,它使用axios.post
向我的服务器发出请求。我尝试将 blob 转换为图像并将其存储在变量中,但我不确定为什么img.onload
从不火灾。
export default function Navbar() {
const isAuth = window.localStorage.getItem('isAuth');
const [img1, setImg1] = useState('');
useEffect(() => {
axios.post('http://localhost:8080/nav', {id: isAuth})
.then((response) => {
const blob = new Blob([response.data], {type: 'image/jpeg'});
const url = URL.createObjectURL(blob);
const img = new Image();
img.src = url;
img.onload = () => {
console.log("Image Loaded");
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height);
const dataURL = canvas.toDataURL(blob.type);
setImg1(dataURL);
};
})
.catch((error) => {
console.log(error);
});
}, [isAuth]);
return (...)
}
我的服务器端代码查询数据库并返回一个 blob(如果存在)。
app.post('/nav', (req, res) => {
const id = req.body.id;
db.query("SELECT img1 FROM users WHERE id = ? ", id, (err, result) => {
if (err)
console.log(err);
if (result.length === 0)
res.json({ data: 'false' });
else
res.json({ data: result[0].img1 });
})
})
客户端和服务器之间是否存在信息脱节?还有其他方法可以解决这个问题吗?