首先我们看一个跨域访问被阻止的例子:
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就讲到这里