Solve the problem of front-end and back-end separation project back-end setting response header that the front-end cannot obtain

Problem Description

In the development of a front-end and back-end separation project, problems such as the back-end setting response header and the front-end being unable to obtain it occurred.
The backend setting response header code is as follows

response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName,"UTF-8"));

Insert image description here
We can see the set response headerContent-Disposition attribute in the browser, but we cannot see the response header we set in the response information received by the front end< a i=2>attribute. Content-Disposition
Insert image description here

problem solved

It turns out that in projects with front-end and back-end separation, in addition to defining the response header, the response header also needs to be exposed so that it can be obtained by the front end. By default, only six response headers are exposed to the outside world, as follows:

Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma

In addition to these six types, if you want to expose other response headers, you need to set them throughAccess-Control-Expose-Headers. The specific code is as follows

response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName,"UTF-8"));

After the setting is successful, you can see the picture below
Insert image description here
At this time, the response information returned to the front end can see the response header set by our back end
Insert image description here
In addition, I set it to Content-Disposition on the backend, but I can’t get it on the frontend through the following method:

let contentDisposition = res.headers['Content-Disposition'];

Finally, I found that the browser automatically converted uppercaseContent-Disposition into lowercasecontent-disposition
and you can successfully obtain it after changing it.

let contentDisposition = res.headers['content-disposition'];

Please see this article for the specific front-end and back-end code to implement file downloads "Vue+elementui implements file packaging and downloading"

Guess you like

Origin blog.csdn.net/weixin_42684368/article/details/132840973