一.创建springboot项目
1.配置application.yml
server:
port: 8091
2 . 第一种解决跨域问题是利用@Configuration配置跨域。
2.1在新建conf
包中创建跨域配置类CorsConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址,所有访问地址
//如果不使用”*”(即允许全部访问源),则可以配置多条访问源来做控制。
// corsConfiguration.addAllowedOrigin("http://localhost:8082/");
// corsConfiguration.addAllowedOrigin("http://test.aimaonline.cn/");
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
3 .正在新建controller包下创建一个userController
@Controller
public class userController {
@GetMapping("/hello1")
@ResponseBody
public String hello1(){
return "hello1";
}
@PostMapping("/hello2")
@ResponseBody
public String hello2(String username,int password){
return username;
}
}
4.第二种比较简单,就是在上面userController
加上@CrossOrigin
就能实现跨域
二.新建一个前端界面
1.在idea中新建空白文件夹,拖入所需文件,目录如下:
2 .在test.html写ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>跨域test</title>
</head>
<body>
<button id="btn">按钮1</button>
<button id="btn2">按钮2</button>
<div id="app"></div>
<script src="js/jquery-3.2.1.js"></script>
<script>
$(function () {
$("#btn").on("click",function () {
$.get('http://localhost:8091/hello1', function (msg) {
$("#app").html(msg);
});
})
$("#btn2").on("click",function () {
$.post(
'http://localhost:8091/hello2',
{username:"haha",password:123456},
function (msg) {
$("#app").html(msg);
});
})
})
</script>
</body>
</html>