node.js - 显示图像时,Object.parse 的位置 0 处出现 JSON 中的意外标记

标签 node.js angular mongodb express mean

我正在尝试将图像存储在 mongodb 中并将其显示回 Angular。我已完成上传,但在尝试显示时出现错误。我在 POSTMAN 中测试了我的 API。它运行良好。我认为错误是由于响应类型引起的。

API

    get('/images',(req, res, next) => {
      const user = AuthBase.getUser(req, res);
      this.model.findOne({\[this.userForeignKey\]: new mongoose.Types.ObjectId(user._id)}, (err, image) => {
          if (err) {
              res.sendStatus(400);
          }
          // stream the image back by loading the file
          res.setHeader('Content-Type', 'image/jpeg'); 
          fs.createReadStream(path.join(UPLOAD_PATH, image.filename)).pipe(res);
//if I add res.json(image) here, I am not getting any error but the Image is getting broken        
 })
    });][1] 

服务

getImage(): Observable<any> {
  return this.http.get(`/api/images`);
}

组件

images:[]
  getImage() 
  {
 this.patientService.getImage().subscribe(
    data =>{ 
   this.images = [data]; 
   console.log(data); },
    error => console.log(error) ); 
  }

最佳答案

在 get 请求中包含响应类型

getImage(): Observable<any> {
  return this.http.get(`/api/images`,{ responseType: 'blob' });
}

关于node.js - 显示图像时,Object.parse 的位置 0 处出现 JSON 中的意外标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51220862/

相关文章:

html - 使用 websockets 和 node.js 的 Web 应用程序

javascript - 如何在 Node.js 中使用带有 Promise 的 MongoDB?

angular - 通过管道传输到我的自定义过滤器中的对象数组始终显示为零长度

javascript - 使用 api 显示列表的 Angular 8 问题

java - 使用 MongoDB Java 驱动程序更新嵌入式文档中的字段?

mongodb - 在 Meteor 中使用带有参数的#each

mongodb - 访问 mongoDB 集合中的数组

node.js - 使用 Phusion Passenger 的 Next.js 应用程序的启动脚本(使用文件启动生产构建)?

node.js - 在 AWS lambda 上列出 cognito 用户池用户

angular - Angular中的Highcharts工具提示的单元测试