zoukankan      html  css  js  c++  java
  • Spring Mvc 跨域访问

    Spring Mvc 跨域访问

    跨域访问

    当前页面渲染请求为 http://localhost:8080/index.html

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <title>CORS 示例</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" ></script>
    </head>
    <body>
    <div id="message"></div>
    </body>
    <script>
    $(document).ready(function(){
    // Ajax 跨域 GET 请求
    $.get( "http://api.rest.org:8080/hello", function( data ) {
    alert( data );
    $( "#message" ).html( data );
    });
    });
    </script>
    </html>
    

    注解驱动 @CrossOrigin

    • 在允许跨域访问的接口上添加@CrossOrigin注解
        @CrossOrigin("*")
        @GetMapping("/hello")
        public String hello() {
            return "hello";
        }
    

    代码驱动 WebMvcConfigurer#addCorsMappings

    • 编写配置类继承WebMvcConfigurer重写addCorsMappings方法
    @Configuration
    public class RestWebMvcConfigurer implements WebMvcConfigurer {
     public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*");
        }
    }
    

    可以看到响应头里含有Access-Controller-Allow-Origin:*的键值对

  • 相关阅读:
    codeforces 862B
    codeforces 863B
    codeforces 864B
    codeforces 867B
    codeforces 868B Race Against Time
    codeforces 869B The Eternal Immortality
    CodeForces
    nyoj 括号配对问题(模拟栈的过程)
    HDU
    nyoj 119 士兵杀敌(三)线段树
  • 原文地址:https://www.cnblogs.com/fjf3997/p/13063731.html
Copyright © 2011-2022 走看看