繁体   English   中英

网络显示 http 响应未定义 Angular 13

[英]Network shows http response undefined Angular 13

我正在尝试从NestJS服务器获取产品。产品即将推出,但附加的图像不可见。根据一些 stackoverflow 答案,我们必须将即将到来的图像转换为它们的格式。但问题是我收到了一个entire object list not just images.So I tried to seprate the images from subscribed data using map function.And after implementing some conversion function logic, I'm getting undefined in Network Panel

在以下屏幕截图中,您可以在网络选项卡中看到undefined with text/html type响应,在网络选项卡详细信息下方,所有图像路径都在控制台面板中可见

在此处输入图像描述

在 service.ts 文件中获取方法。通过设置responseType:'blob' gives error,so I didn't set blob

public getallbooks(): Observable<any> {
    return this.httpclient.get(
      `${this.API_SERVER}/books`
      //  {
      //   responseType: 'blob',
      // }
    );
  }

这里的 component.ts 文件是 function 用于转换图像并显示产品

  image!: any;
  results?: Book[];

ngOnInit() {
    this.apiService.getallbooks().subscribe((data: Book[]) => {
      this.results = data;
      const arr = this.results?.map((i) => {
        return i.coverimage;
      });
      this.createImageFromBlob(arr);
      console.log(this.results);
      console.log(arr);
});
 }
createImageFromBlob(image: any) {
    let reader = new FileReader();
    (reader.onload = () => {
      this.image = this.sanitizer.bypassSecurityTrustUrl(
        reader.result as string
      );
    }),
      false;
    if (image) {
      reader.readAsDataURL(new Blob([this.image]));
    }
  }

html代码

<div class="grid" *ngFor="let result of results">
      <div class="blog-card spring-fever" style="padding: 0.5rem; z-index: 100">
        <img
          class="image"
          [src]="'http://localhost:3000/' + image | safeurl"
          alt=""
          height="400px"
          width="250px"
          style="border: 1px solid red"
        />

我也认为这也可能是后端问题

NestJs文件上传代码

@Controller('images')
export class ImagesController {
  static imageUrl: string;
  constructor(private readonly bookservice: BooksService) {}

  @Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './assets/',
        filename: (req, file, cb) => {
          const filename: string = Array(10)
            .fill(null)
            .map(() => Math.round(Math.random() * 16).toString(16))
            .join('');
          return cb(null, `${filename}${extname(file.originalname)}`);
        },
      }),
    }),
  )
  uploadFile(@UploadedFile() file: Express.Multer.File, @Request() req) {
    console.log(file);
    return this.imageUrl(file);
  }

  private imageUrl(file: Express.Multer.File) {
    ImagesController.imageUrl = `./assets/${file.filename}`;
    return ImagesController.imageUrl;
  }
}

嵌套 Js books.service.ts 业务逻辑上传带有图片路径附件的产品

async addbooks(book: Book): Promise<bookdocument> {
    book.coverimage = ImagesController.imageUrl;
    return await this.book_model.create(book);
  }

NestJs 端点上传书

@Post()
  async addbooks(@Body() book: Book) {
    const uplaodbook = await this.bookservice.addbooks(book);
    return uplaodbook;
  }

因此,就我而言,我有一个书籍清单,每本书都有其图像的路径。 我正在使用ngFor并使用路径设置图像src 这是正确的方法。 但是图像不可见,网络将图像显示为text/html类型。 这里的实际问题不是type ,实际问题出在我的URL中。我在 NestJs 服务器中有一个名为assets的文件夹,该文件夹位于root下,并且我已经设置了图像的路径(在 NestJs 文件上传中代码),就像这样./assets/ 这也是设置目标文件夹的正确方法。我能够在浏览器中看到像http://localhost:3000/imagename.png这样的图像,这意味着我的服务器配置为通过根 URL 服务/提供我的图像这就是为什么我可以访问它们http://localhost:3000/imagename.png 但是我的 api 返回的图像格式包含./assets/中的 ./assets/。 所以用下面的代码

<div *ngIf="image">
          <img
            class="image"
            [src]="'http://localhost:3000/' + image | safeurl"
            alt=""
            height="400px"
            width="250px"
            style="border: 1px solid red"
          />
        </div>

I am assuming that I'm hitting the Url like this http:localhost:3000/imagename.png with pipe safurl to sanitize and tell Angular that this url is safe. 但实际上 Angular 看到 URL 就像这样http:localhost:3000/./assets/imagename.png 这是注意正确的 URL 格式 网址不适用于. 或者, .Also因为我的服务器是在root配置的,这个url http;//localhost:3000/assets/imagename.png也是错误的。而root意味着,无论在root设置什么,之后都可以直接访问您的服务器的端口号。 示例http://localhost:YourServerPortNumber/TheThing_Set_at_Root

所以这个问题的解决方案如下

src="http://localhost:3000/{{
              result.coverimage.replace('./assets/', '')
            }}"

还有这个

<div *ngIf="result.coverimage">
          <img
            class="image"
            src="http://localhost:3000/{{
              result.coverimage.replace('./assets/', '')
            }}"
            alt=""
            height="400px"
            width="250px"
            style="border: 1px solid red"
          />
        </div>

使用上面的.replace('./assets/', '')我们正在删除./assets/并用''空白空间替换它。 所以现在 URL 是这种格式http://localhost:3000/imagename.png

此外,我现在可以删除safeurl pipe ,因为它是localhost ,但在生产模式中,我将需要 pipe。 即使使用 localhost,也可能有人需要 pipe。

现在我也不需要createImageFromBlob() function 和map或其他数组方法从订阅数据中提取所有图像,只需像这样编写代码来显示数据

ngOnInit() {
    this.apiService.getallbooks().subscribe((data: Book[]) => {
      this.results = data;
      console.log(this.results);
  });
  }

我希望我自己正确理解了这些事情并正确解释了它们

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM