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

前言

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

java 复制代码
@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();删除即可解决。

java 复制代码
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
相关推荐
努力也学不会java19 小时前
【设计模式】状态模式
java·设计模式·状态模式
闲人编程2 天前
前端形态与样式风格:从古典到现代的视觉语言演进
前端·css·状态模式·组件·js·风格·响应式
摸鱼仙人~5 天前
后端错误处理的艺术:BusinessException 与 ResultUtils 的完美分工
状态模式
上优5 天前
Vue3纯前端同源跨窗口通信移动AGV小车
前端·vue.js·状态模式
南山二毛6 天前
机器人控制器开发(部署——软件打包备份更新)
机器人·状态模式
阿里嘎多哈基米6 天前
SQL 层面行转列
数据库·sql·状态模式·mapper·行转列
bikong77 天前
状态模式(State Pattern)——网络连接场景的 C++ 实战
状态模式
TechNomad7 天前
设计模式:状态模式(State Pattern)
设计模式·状态模式
mit6.8249 天前
[Upscayl图像增强] docs | 前端 | Electron工具(web->app)
前端·人工智能·electron·状态模式
卑微的小鬼9 天前
Go语言的编译和运行过程
开发语言·golang·状态模式