Spring Boot (4) CORS

Spring Boot (4) CORS

Scroll Down

CORS 是由 W3C 制订的一种跨域资源共享技术标准, 为了解决前端跨域请求.

Spring Boot CORS

细粒度的配置

/**
 * 跨域 书控制器
 *
 * @Auther: MaWenyi
 * @Date: 2019/6/25
 * @Description: com.iscolt.cors.web.controller
 * @version: 1.0
 */
@RestController
@RequestMapping(value = "book")
public class BookController {

    /**
     * value 表示域
     * maxAge 表示请求有效期
     * allowedheaders 表示允许的请求头
     *
     * @param name
     * @return
     */
    @PostMapping("/")
    @CrossOrigin(value = "http://localhost:8086", maxAge = 1800, allowedHeaders = "*")
    public String addBook(String name) {
        return "receive:" +name;
    }

    @DeleteMapping("/{id}")
    @CrossOrigin(value = "http://localhost:8086", maxAge = 1800, allowedHeaders = "*")
    public String deleteBookById(@PathVariable Long id) {
        return String.valueOf(id);
    }
}

全局配置

/**
 * 配置全局跨域
 * 
 * @Auther: MaWenyi
 * @Date: 2019/6/25
 * @Description: com.iscolt.cors.config
 * @version: 1.0
 */
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/book/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .maxAge(1800)
                .allowedOrigins("http://localhost:8086");
    }
}

测试

新建一个项目, 引入jquery

static 下新建index.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<div id="contentDiv"></div>
<div id="deleteResult"></div>
<input type="button" value="提交数据" onclick="getData()"><br>
<input type="button" value="删除数据" onclick="deleteData()"><br>
<script>
    function getData() {
        $.ajax({
            url: 'http://localhost:8085/book/',
            type: 'post',
            data: {name:'三国演义'},
            success: function (msg) {
                $("#contentDiv").html(msg)
            }
        })
    }
    function deleteData() {
        $.ajax({
            url: 'http://localhost:8085/book/99',
            type: 'delete',
            success: function (msg) {
                $("#deleteResult").html(msg)
            }
        })
    }
</script>
</body>
</html>
支付宝 微信