后端使用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");
相关推荐
Yvonne爱编码8 小时前
前端工程化进阶:从搭建完整项目脚手架到性能优化【技术类】
前端·状态模式
Mr_sun.13 小时前
Day02——基础数据开发-服务管理前端
前端·状态模式
xiaoxue..14 小时前
Zustand 状态管理:轻量高效的 React 状态解决方案✨
前端·react.js·面试·状态模式·zustand
数据库知识分享者小北2 天前
从极速复制“死了么”APP,看AI编程时代的技术选型
数据库·阿里云·状态模式·ai编程·supabase
桃子叔叔2 天前
react-wavesurfer录音组件2:前端如何处理后端返回的仅Blob字段
前端·react.js·状态模式
牵牛老人2 天前
Qt后端开发遇到跨域问题终极解决方案 与 Nginx反向代理全解析
qt·nginx·状态模式
C_心欲无痕2 天前
有限状态机在前端中的应用
前端·状态模式
雨中散步撒哈拉2 天前
22、做中学 | 高一下期 | Golang反射
开发语言·golang·状态模式
小陈phd2 天前
langGraph从入门到精通(四)——基于LangGraph的State状态模式设计
python·microsoft·状态模式
stella·2 天前
后端二进制文件,现代前端如何下载
前端·ajax·状态模式·axios·request·buffer·download