SpringBoot实现跨域访问

9 篇文章 1 订阅
9 篇文章 0 订阅

首先我们看一个跨域访问被阻止的例子:

1.定义一个Controller

@Controller
public class HelloWorldController {

    @RequestMapping("")
    public String index() {
        return "index";
    }


}

controller会让我们去访问index.html页面

2.在src/main/resources下面定义这个index.html页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>CORS 示例</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" ></script>
</head>
<body>
<div id="message"></div>
</body>

<script>
$(document).ready(function(){
     // Ajax 跨域 GET 请求
     $.get( "http://api.rest.org:8080/hello", function( data ) {
                alert( data );
                $( "#message" ).html( data );
        });
});
</script>

</html>

我们访问localhost:8080的HelloWorldController,然后得到的index.html页面发送一个ajax请求到http://api.rest.org:8080/hello中去。这里的api.rest.org也是我们本机的127.0.0.1,这里为了模拟,用了这个域名来代替。接下来我们在定义一个restController:

@RestController
public class HelloWorldRestController {


    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

}
@SpringBootApplication
public class SpringBootRestBootstrap {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootRestBootstrap.class, args);
    }
}

运行起来,不出意外会报错,因为出现了跨域访问,跨域访问其实请求已经到了服务器,只不过服务器拦截了请求,不会应答给浏览器,这一点尤为注意~~

那么怎么实现跨域访问呢,第一种方式只需要在HelloWorldRestController中加一个注解@CrossOrigin("*"):

@RestController
public class HelloWorldRestController {

    @CrossOrigin("*")
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

}

这样就可以跨域访问了

第二种方式是代码的实现方式,新增一个类:

@Configuration
public class RestWebMvcConfigurer implements WebMvcConfigurer {


    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*");
    }


}

OK就讲到这里

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值