后端使用Response出现跨域问题

后端使用Response出现的跨域问题

今天联调文件下载的接口,由于自己用postman测试一直都没问题,但是在和前端联调的时候前端就会出现如下跨域的报错

后端使用Response出现跨域问题_第1张图片

    @ApiOperation("下载附件")
    @PostMapping(value = "/download")
    public void  downloadFile(@RequestBody List<Long> fileId) {
        ServletRequestAttributes servletRequestAttributes =  (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        FileBinary fileBinary=  fileReportApiClient.download(fileId);
        byte[] bytes = fileBinary.getData();
        try {
            // 清空response
//            response.reset();
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(new Date().getTime() + ".zip", "utf-8"));
            OutputStream ouputStream = response.getOutputStream();
            ouputStream.write(bytes);
            ouputStream.flush();
            ouputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

项目的框架本身就是加了跨域处理的

@Configuration
public class CorsConfig {@Bean
   public CorsFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedOriginPattern("*");
    config.setAllowCredentials(true);
    config.addAllowedMethod("*");
    config.addAllowedHeader("*");
    UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
    configSource.registerCorsConfiguration("/**", config);
    return new CorsFilter(configSource);
        }

}

但response.reset()的时候把它给重置了,因此就造成前端无法下载并报跨域问题。于是尝试在reset()下面加上这几行代码,就可以解决跨域问题了。但是由于我已经配置了跨域,就直接把response.reset();去掉就好了

response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");

你可能感兴趣的:(java基础,java,json,servlet)