我在后端有一个保存图像的路径。 我可以从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">
它不会返回任何错误,并且stil不会显示图像。
如果我尝试点击bypassSecurityTrustUrl
函数内部的路径进行测试,然后删除* ngIf,它将返回:
null:1 GET http://localhost:4200/null 404 (Not Found)