后端使用response.reset()导致出现跨域问题

前言

今天联调文件下载的接口,由于自己用postman测试一直都没问题,但是在和前端联调的时候前端就会出现如下跨域的报错,但是项目是做了统一的跨域处理的,代码类似于下面:

@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();
        }
    }

解决方式

但是项目是做了统一的跨域处理的,后来通过查询资料,发现是response.reset();导致的,正常的respon会带下面的数据,但是.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");

你可能感兴趣的:(状态模式)