后端使用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");
相关推荐
小码过河.2 小时前
设计模式——状态模式
ui·状态模式
前端不太难5 小时前
HarmonyOS 后台机制,对实时游戏意味着什么?
游戏·状态模式·harmonyos
前端不太难3 天前
Flutter / RN / iOS 的状态策略,该如何取舍?
flutter·ios·状态模式
小夏卷编程4 天前
jeecg boot 3.2.0 用户token刷新在线用户显示问题
状态模式
Yvonne爱编码7 天前
前端工程化进阶:从搭建完整项目脚手架到性能优化【技术类】
前端·状态模式
Mr_sun.7 天前
Day02——基础数据开发-服务管理前端
前端·状态模式
xiaoxue..7 天前
Zustand 状态管理:轻量高效的 React 状态解决方案✨
前端·react.js·面试·状态模式·zustand
数据库知识分享者小北8 天前
从极速复制“死了么”APP,看AI编程时代的技术选型
数据库·阿里云·状态模式·ai编程·supabase
桃子叔叔8 天前
react-wavesurfer录音组件2:前端如何处理后端返回的仅Blob字段
前端·react.js·状态模式
牵牛老人8 天前
Qt后端开发遇到跨域问题终极解决方案 与 Nginx反向代理全解析
qt·nginx·状态模式