跨域问题的三种解决方式

第一种方式,全局配置

@Configuration
public class kuayu implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                     //allowedOrigins   里面的值,可以是请求时Origins的具体值,要么是 * ,接受任意域名请求
                .allowedOrigins("*")    
                   //allowedMethods   里面的值,表明服务器支持的所有跨域请求方法
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
                   //allowCredentials  表示 是否允许发送Cookie,默认不发送
                .allowCredentials(true)
                   //maxAge 表示本次预检请求的有限期,单位秒
                .maxAge(3600)
                   //allowedHeaders 表示跨域请求时,XMLHttpRequest对象的getResponseHeader()拿到的字段
                .allowedHeaders("*");
                 
    }
}

第二种方式,基于过滤器

@WebFilter(filterName = "CorsFilter")
@Configuration
public class kuayu implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response1=(HttpServletResponse)response;
        response1.setHeader("Access-Control-Allow-Origin","*");
        response1.setHeader("Access-Control-Allow-Credentials","true");
        response1.setHeader("Access-Control-Allow-Method","GET,POST,PUT,DELETE,PATCH");
        response1.setHeader("Access-Control-Max-Age","3600");
        response1.setHeader("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");
        chain.doFilter(request,response);

    }
}

第三种,注解(最小级别,精确到单个请求级别)

public class kuayu {
@CrossOrigin(origins = "http://localhost:4000")
@GetMapping("goods-url")
    public Response queryGoodsWithGoodsUrl(@RequestParam String goodsUrl) throws Exception{}
}

上面三者选其一,一般来说第一种或第二种在几个域中使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值