简体   繁体   English

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

[英]Network shows http response undefined Angular 13

I'm trying to get the products from NestJS server.And the products are coming but the attached images are not visible.According to some stackoverflow answers we have to convert the coming images into their format.But the thing is I'm receiving an 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我正在尝试从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

In the following screen shot you can see the undefined with text/html type response in Network tab,and below the network tab details,all the image paths are visible in console panel在以下屏幕截图中,您可以在网络选项卡中看到undefined with text/html type响应,在网络选项卡详细信息下方,所有图像路径都在控制台面板中可见

在此处输入图像描述

get method in service.ts file.By setting responseType:'blob' gives error,so I didn't set blob在 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 file here is the function for converting images and also displaying the product这里的 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 code 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"
        />

I also think this might be a backend issue as well我也认为这也可能是后端问题

NestJs file upload code 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;
  }
}

Nest Js books.service.ts business logic to upload product with image path attachement嵌套 Js books.service.ts 业务逻辑上传带有图片路径附件的产品

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

NestJs endpoint to upload book NestJs 端点上传书

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

So in my case I had a list of books and each book has path for its image.因此,就我而言,我有一个书籍清单,每本书都有其图像的路径。 I was using ngFor and set the image src with the path.我正在使用ngFor并使用路径设置图像src That is the right way.这是正确的方法。 But the images were not visible and Network was showing images as text/html type.但是图像不可见,网络将图像显示为text/html类型。 The actual issue here was not the type ,the actual issue was in my URL .I had a folder in NestJs server by the name of assets ,that is present at root , and I had set the path for the images(in NestJs file upload code), like this ./assets/ .这里的实际问题不是type ,实际问题出在我的URL中。我在 NestJs 服务器中有一个名为assets的文件夹,该文件夹位于root下,并且我已经设置了图像的路径(在 NestJs 文件上传中代码),就像这样./assets/ That is also the correct way to set the destination folder.I was able to see the images at browser like this http://localhost:3000/imagename.png ,and that means my server configured to server/serve my images over root URL that's why I can access them http://localhost:3000/imagename.png .这也是设置目标文件夹的正确方法。我能够在浏览器中看到像http://localhost:3000/imagename.png这样的图像,这意味着我的服务器配置为通过根 URL 服务/提供我的图像这就是为什么我可以访问它们http://localhost:3000/imagename.png But my api was returning images in a format that contains ./assets/ in the URL.但是我的 api 返回的图像格式包含./assets/中的 ./assets/。 So with the following code所以用下面的代码

<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. 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. But actually Angular was seeing the URL like this http:localhost:3000/./assets/imagename.png .但实际上 Angular 看到 URL 就像这样http:localhost:3000/./assets/imagename.png And this is note the correct URL Format .这是注意正确的 URL 格式 Urls don't work with .网址不适用于. or , .Also becasue my server is configured at root, this url http;//localhost:3000/assets/imagename.png is also wrong.And root means that, whatever the thing is set at root , that is directly access able after your server's port number.或者, .Also因为我的服务器是在root配置的,这个url http;//localhost:3000/assets/imagename.png也是错误的。而root意味着,无论在root设置什么,之后都可以直接访问您的服务器的端口号。 Example http://localhost:YourServerPortNumber/TheThing_Set_at_Root .示例http://localhost:YourServerPortNumber/TheThing_Set_at_Root

So the solution for this issue is the following所以这个问题的解决方案如下

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

And also this还有这个

<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>

With above .replace('./assets/', '') we are removing the ./assets/ and repalcing it with '' empty space.使用上面的.replace('./assets/', '')我们正在删除./assets/并用''空白空间替换它。 So now URL is in this format http://localhost:3000/imagename.png .所以现在 URL 是这种格式http://localhost:3000/imagename.png

Also I can remove safeurl pipe for now beacuse it is localhost ,but in prodction mod I will be needing that pipe.此外,我现在可以删除safeurl pipe ,因为它是localhost ,但在生产模式中,我将需要 pipe。 And It might happen that even with localhost somebody might need the pipe.即使使用 localhost,也可能有人需要 pipe。

Also now I don't need the createImageFromBlob() function and the map or other array methode to extract all the images from subscribed data,and simply you can write your code like this to display the data现在我也不需要createImageFromBlob() function 和map或其他数组方法从订阅数据中提取所有图像,只需像这样编写代码来显示数据

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

I hope I understood the things myself correctly and explained them correctly我希望我自己正确理解了这些事情并正确解释了它们

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

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