栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

记一次SpringBoot解决CROS跨域问题(CROS)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

记一次SpringBoot解决CROS跨域问题(CROS)

记一次SpringBoot解决CROS跨域问题(CROS) 使用注解@CrossOrigin(局部跨域

后端创建注入切面

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@documented
public @interface CrossOrigin {
    //这origins和value是一样的
    //允许来源域名的列表,例如 'www.jd.com',匹配的域名是跨域预请求 Response 头中的'Access-Control-Aloow_origin' 
    //字段值。不设置确切值时默认支持所有域名跨域访问。
    @AliasFor("origins")
    String[] value() default {};
    @AliasFor("value")
    String[] origins() default {};
    //高版本下Spring2.4.4使用originPatterns 而不是value 和 origins
    String[] originPatterns() default {};

    //跨域请求中允许的请求头中的字段类型, 该值对应跨域预请求 Response 头中的 'Access-Control-Allow-Headers' 字段值。
    //不设置确切值默认支持所有的header字段(Cache-Controller、Content-Language、Content-Type、
    //Expires、Last-Modified、Pragma)跨域访问
    String[] allowedHeaders() default {};

    //跨域请求请求头中允许携带的除Cache-Controller、Content-Language、Content-Type、Expires、Last-Modified、
    //Pragma这六个基本字段之外的其他字段信息,对应的是跨域请求 Response 头中的 'Access-control-Expose-Headers'字段值
    String[] exposedHeaders() default {};

    //跨域HTTP请求中支持的HTTP请求类型(GET、POST...),不指定确切值时默认与 Controller 方法中的 methods 字段保持一致。
    RequestMethod[] methods() default {};

    //该值对应的是是跨域请求 Response 头中的 'Access-Control-Allow-Credentials' 字段值。
    //浏览器是否将本域名下的 cookie 信息携带至跨域服务器中。默认携带至跨域服务器中,但要实现 cookie 
    //共享还需要前端在 AJAX 请求中打开 withCredentials 属性。
    String allowCredentials() default "";

    //该值对应的是是跨域请求 Response 头中的 'Access-Control-Max-Age' 字段值,表示预检请求响应的缓存持续的最大时间,
    //目的是减少浏览器预检请求/响应交互的数量。默认值1800s。设置了该值后,浏览器将在设置值的时间段内对该跨域请求不再发起预请求
    long maxAge() default -1;
}
后端在跨域接口处使用切面(Controller)

@RestController
@RequestMapping("/minio")
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class MiniFilecontroller {

    @Autowired
    private MinioFileService minioFileService;

    
    @DeleteMapping("/{fileName}")
    public R removeByFileName(@PathVariable String fileName) {
        return this.minioFileService.deleteFile(fileName);
    }

    
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) {
        return this.minioFileService.uploadFile(file);
    }

    
    @GetMapping("/{fileName}")
    public void file(@PathVariable String fileName, HttpServletResponse response) {
        this.minioFileService.getFile(fileName, response);
    }
} 
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/590604.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号