Home > other >  Spring boot does not seem to expose a custom header to my frontend
Spring boot does not seem to expose a custom header to my frontend

Time:08-27

I am using a Spring Boot backend and an Angular frontend and want to implement the functionality of downloading a pdf file.

For this purpose, I have implemented the following handler in my REST-controller:

  @GetMapping("/{id}")
  public ResponseEntity<Resource> getPdf(@PathVariable Long id) {
    Pdf pdf = this.pdfService.getPdf(id);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("filename", pdf.getId());
    httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""   pdf.getId()   "\"");
    return ResponseEntity.ok()
      .headers(httpHeaders)
      .body(new ByteArrayResource(pdf.getContent()));
  }

In my frontend, I am using file-saver to save the file after receiving the response from my backend. File-saver requires a file name, which I want to set by reading the filename from the http response header. The problem is that the header, which I have clearly set in my backend, is not visible in my client. When logging the response, I can only see the following headers:

response headers

I have no clue why I cannot see the header I have set in my backend.

After doing some research, I found out that maybe, just maybe, it has something to do with an access-control-allow-origin option I would need to set for custom Http headers. I played around with it, but didn't manage to come up with a solution.

So I am asking: Has anyone seen this problem before?

CodePudding user response:

most likely there are headers in the response, however you can not read them from JS for CORS security reasons.

you should add Access-Control-Expose-Headers header to expose these headers explicitly

  • Related