【发布时间】:2020-03-01 23:48:06
【问题描述】:
我在后端有一条路径,用于保存我的图像。 我可以从 mongo 获取路径并以角度重现它,但是,当我使用带有 src 绑定的标签时,它不会显示图像和任何错误:
组件内的路径:
this.profileService.getImg().subscribe(res => this.imagePath = res['img']);
控制台日志的返回:
console.log(this.imagePath);
http://localhost:3000/avatars/5db84cdf4c6efe073864f9e7.jpeg
html标签:
<img [src]="imagePath">
我尝试了在其他帖子中找到的几种方法,但都无法成功。 知道发生了什么以及如何解决这个问题?
更新和更多详情
在服务器端,我通过这种方式从 mongo 返回路径:
router.get('/:id', (req, res, next) => {
Avatar.getAvatarById(req.params.id, (err, avatar) => {
if(err) throw err;
if(!avatar){
return res.json({success: false, msg: 'No avatars found'});
}
res.json({
success: true,
avatar: avatar
});
});
});
Avatar.getAvatarById 是:
module.exports.getAvatarById = function(id, callback){
const query = { avatar: {$regex: ".*"+id+".*" }}
Avatar.findOne(query, callback);
}
我正在像这样公开头像路径:
app.use('/avatars', express.static('avatars'));
当我尝试通过在浏览器中点击http://localhost:3000/avatars/5db84cdf4c6efe073864f9e7.jpeg 来访问路径时,它会返回 json 而不是渲染图像。
{
"success":true,
"avatar": {
"_id":"5dc17fc9f383424158c59754",
"avatar":"http://localhost:3000/avatars/5db84cdf4c6efe073864f9e7.jpeg","__v":0
}
}
还尝试通过使用 bypassSecurityTrustResourceUrl 来克服安全性并使用 *ngIf 来显示 url 存在时。
this.photoUrl = this.sanitizer.bypassSecurityTrustUrl(res['avatar']['avatar']);
<img *ngIf="photoUrl" [src]="photoUrl">
它不返回任何错误并且仍然不显示图像。
如果我尝试通过点击bypassSecurityTrustUrl 函数内的路径进行测试,并删除 *ngIf,它会返回:
null:1 GET http://localhost:4200/null 404 (Not Found)
【问题讨论】:
-
嗨迭戈。您是否将图像文件夹公开为静态文件夹并将其连接到
/avatars?现在您只能从后端获取图像路径,但您没有执行任何步骤来公开该文件夹的内容(至少从您共享的代码中)..
标签: node.js angular imageview mean-stack