利用@Configuration配置跨域请求
代码实现如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 的CORS配置类
* @author xiaofei
*/
@Configuration
public class CustomCorsConfig {
@Bean
public WebMvcConfigurer getConfig(){
return new WebMvcConfigurerAdapter() {
// 重新找个方法
@Override
public void addCorsMappings(CorsRegistry registry) {
// 允许站外8081端口来访问api找个接口
// addAllowedOrigin("*"); // 设置访问源地址
// addAllowedHeader("*"); // 设置访问源请求头
// addAllowedMethod("*"); // 设置访问源请求方法
registry.addMapping("/api/**");
}
};
}
}
写一个ApiControll:
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
/**
* api接口
*
* @author xiaofei
*/
@RestController
@RequestMapping("/api/")
public class ApiController {
@RequestMapping("get")
public HashMap<String, Object> get(@RequestParam String name) {
HashMap<String, Object> map = new HashMap();
map.put("name", name);
map.put("pwd", 123456);
return map;
}
}
在application.properties中配置:
server.port=8080
然后访问:http://localhost:8080/api/get?name=xiaofei 测试
{"name":"xiaofei","pwd":123456}
在创建另一个项目测试
application.properties中配置:
server.port=8081
新建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试CORS</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
</head>
<body>
<button id="btu" >按钮</button>
<script>
$("#btu").click(function () {
$.post(
// 请求路径
"http://localhost:8080/api/get?name=xiaofei",
function (map) {
console.log(map);
}
);
});
</script>
</body>
</html>
访问:
server.port=8081