Springboot跨域

这一次让咋们搞定跨域!(第一节 <服务端方式> )

技术栈

  1. java端:
    • springboot
    • springmvc
    • h2(这个是数据库,为了显得有仪式感哈哈,不想弄这个可以在Controller直接返回Stirng就行)
  2. web端

那么就让我们现在开始吧

可以看到浏览器的控制台已经报错了,根据第一节跨域常见的错误可以知道是因为服务器端后台没有允许OPTIONS请求

那么服务器后端如何允许options请求呢

sprng官方已经给大家作了指导,建议大家还是应该静下心来去看看官方的文档地址点击这里,如何时间不多或者英文不好直接看这篇文章也行

启用CORS

  • (Controller Method CORS Configuration)控制器方法CORS配置
  • (Global CORS configuration)全局CORS配置

我的controller是这么写的

注意现在是不能进行跨域请求的
@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping("/test")
    private List quertCoffee(){
        return testService.showDate();
    }
}
Controller Method CORS Configuration

为了使响应中包含CORS访问控制标头,你必须对单个controller上面添加这个注释@CorssOrigin例如

@RestController
@CrossOrigin(origins = "http://localhost:8080") 此注解仅针对特定方法启用跨域资源共享
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping("/test")
    private List quertCoffee(){
        return testService.showDate();
    }
}
在此实例中,我们仅允许http://localhost:8080发送跨域请求

请求成功了

Global CORS configuration

除了基于细粒度得配置,还可以设置一些全局配置,这类似使用Filter这是controller层

@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping("/test")
    private List quertCoffee(){
        return testService.showDate();
    }
}

直接在Applicayion类中添加cors映射,就是有主方法的哪个类

@Slf4j
@SpringBootApplication
public class KuayudemoApplication{

    public static void main(String[] args) {
        SpringApplication.run(KuayudemoApplication.class, args);
    }
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/test").allowedOrigins("http://localhost:8080");
                如果要对请求的方法进行限制用.allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")  
                如果要携带Cookie,可以用这个方法 .allowCredentials(true)
            }
        };
    }
}
在这里你可以使用通配符号*,进行粗粒度的跨域请求处理

这里也成功了这就是关于springboot如何解决跨域问题的教程了,下一节将会讲解如何用Nginx配置跨域!

有兴趣的可以关注公众号[月便士],希望里面的东西可以帮助到你,大家一起成长.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值