1
我試圖在Angular2中顯示來自Nodejs響應的圖像。Node.Js/Express + Angular2圖像發送和顯示圖像
節點:
router.get('/users/avatar', function(req, res){
res.sendFile(req.user.avatarName, {
root: path.join(__dirname+'/../uploads/')
}, function (err) {
if (err) {
console.log(err);
}
});
});
和Angular2
//userService.ts
getAvatar(): Observable<any>{
return this.http
.get(this.protectedUrl +'/avatar', {headers: this.protectedHeaders})
.map(res => {
return new Blob([res["_body"]], {
type: 'image/png'
})
}).map(blob => {
let urlCreator = window.URL;
return this.sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
})
}
app.component.ts
ngOnInit() {
this.userService.getAvatar().subscribe(response =>{
console.log(response);
this.avatarSrc=response;
});
}
app.component.htm
<div>
<img [src]="avatarSrc">
<div>
這不顯示任何內容,但是我檢查blob url,它顯示「The image」blob:http://localhost:4200/2a723d0c-da55-4bd5-84fd-4895c803c7a5「無法顯示,因爲它包含錯誤。」 那麼我在做什麼錯?
現在好了角度返回 錯誤:請求正文不是blob或ar藍光緩衝器 –
更新了答案,它缺少responseType選項 –