SpringBoot跨域请求

新建一个SpringBoot项目,端口8080,配置CORS:

@Configuration
public class MyWebMVCConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/book/**")//请求路径
                .allowedHeaders("*")//请求头
                .allowedMethods("*")//方法
                .maxAge (1800)
                .allowedOrigins("http://localhost:8081");//支持的域
    }

}

如果不使用类的话,也可以在单独的方法上面配置:

@RestController
@RequestMapping("/book")
public class BookController {

    @PostMapping("/a")
//    @CrossOrigin(value = "http://localhost:8080",maxAge = 1800,allowedHeaders = "*")
    public String addBook(String name){
        return "添加" + name;
    }
    @DeleteMapping("/{id}")
//    @CrossOrigin(value = "http://localhost:8080",maxAge = 1800,allowedHeaders = "*")
    public String deleteBook(@PathVariable Long id){
        return "删除" + String.valueOf(id);
    }
}

新建一个SpringBoot项目,端口8081,建一个html,第一个项目的控制器发送请求,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="application/javascript" src="jquery.min.js"></script>
</head>
<body>
    <div id="contentDiv"></div>
    <div id="deleteResult"></div>
    <input type="button" value="提交数据" id="getData"/><br/>
    <input type="button" value="删除数据" id="deleteData"/><br/>
<script>
    $(document).ready(function () {
        $("#getData").click(function () {
            $.ajax({
                url:'http://localhost:8080/book/a',
                // headers: "Access-Control-Allow-Origin",
                type:'post',
                data:{name:'aaa'},
                success:function (data) {
                    $("#contentDiv").html(data);
                }
            })
        })
        $("#deleteData").click(function () {
            $.ajax({
                url:'http://localhost:8080/book/99',
                // headers: "Access-Control-Allow-Origin",
                type:'delete',
                success:function (data) {
                    $("#deleteResult").html(data);
                }
            })
        })
    })

</script>
</body>
</html>

结果如下:
SpringBoot跨域请求_第1张图片

你可能感兴趣的:(java)