vue axios无法获取响应头字段

vue axios无法获取响应头Content-Disposition字段

默认情况下,header只有六种 simple response headers(简单响应首部)暴露给外部:

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

暴露给外部,意思是既可以在 Network 里看到,也可以在前端代码里获取到他们的值。

private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    workbook.write(response.getOutputStream());
}

如上,对于文件下载类接口,不论是Excel还是Word,一般都是在Content-Disposition里面配置文件名。而Content-Disposition不在其中,所以即使服务器在协议回包里加该字段,但是前端代码获取不到这个数据。

响应首部 Access-Control-Expose-Headers 就是控制暴露的开关,列出哪些首部可以作为响应的一部分暴露给外部。

解决办法:

private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    // 配置
    response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    workbook.write(response.getOutputStream());
}

注意如果有配置跨域,则上面的解决方法无效:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * 跨域配置
 */
@Configuration
public class CorsConfig {
    private static final String ALL = "*";

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // cookie跨域
        config.setAllowCredentials(Boolean.TRUE);
        config.addAllowedMethod(ALL);
        config.addAllowedOrigin(ALL);
        config.addAllowedHeader(ALL);
        // 配置前端js允许访问的自定义响应头
//        config.addExposedHeader("setToken");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}

https://www.cnblogs.com/codesyofo/p/14142197.html

posted @ 2021-05-26 21:02  johnny233  阅读(101)  评论(0编辑  收藏  举报  来源