Java SpringBoot解决CORS跨域问题
学习前后端分离项目中遇到跨域问题,做个笔记。
问题描述
话不多说,上代码。
两个测试dome,用于区分服务器,端口,模拟跨域。
dome1模拟后端服务器接口。
使用spring脚手架创建。
编写controller。
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author leo
* @date 2021-08-29 16:37
* @description:
*/
@RestController
public class TestController {
@GetMapping("/hello")
public String hello(){
return "hello cors";
}
}
配置端口
server.port=8081
dome2模拟前端服务器请求。
使用spring脚手架创建。
在static里面编写index.html。
引入jquery做ajax请求。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="app"></div>
<input type="button" value="get" onclick="getMsg()">
</body>
<script>
function getMsg() {
$.get("http://localhost:8081/hello","",function (data) {
$("#app").html(data)
})
}
</script>
</html>
编写配置
server.port=8080
启动两个服务器,点击dome的请求按钮会出现如图的错误信息。
解决方法
-
使用@CrossOrigin(origins = “http://localhost:8080”)注解,这里的地址就是要放行的请求地址,这里就是dome1中服务器地址。其格式为,http://主机名+端口,可以配置多个,可以作用方法,也可以作用类。
@RestController @CrossOrigin(origins = "http://localhost:8080") public class TestController { //@CrossOrigin(origins = "http://localhost:8080") @GetMapping("/hello") public String hello(){ return "hello cors"; } }
-
使用@CrossOrigin只能解决一个方法或类的请求,很多时候我们所有的请求都需要放行就需要全局配置,编写配置类CORSConfig并实现WebMvcConfigurer接口,重写addCorsMappings方法。
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author leo * @date 2021-08-29 17:46 * @description: */ @Configuration public class CORSConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") //所有的请求 .allowedOrigins("http://localhost:8080") //放行的请求地址 .allowedMethods("*") //放行所有的请求方法 .allowedHeaders("*") //放行所有的请求头 .maxAge(30 * 1000); //探测请求时间 } }
以上两种方法都能解决跨域问题。
结语
前后端分离产生的跨域问题确实让初学者特别烦恼,希望这篇笔记能帮助到更多跟我一样的小白!
好像nginx也可以通过配置解决跨域问题,以后学的了再说吧。