SpringBoot supports AJAX cross-domain requests

Use annotations to solve cross-domain AJAX requests

1. Write a Configuration that supports cross-domain requests

- the first way

- CorsConfig.java

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Handling cross-domain AJAX requests
 * @author Levin
 * @time 2017-07-13
 */
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
    static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS)
                .maxAge(3600);
    }
}

2. HTTP request interface

- HelloController.java

@RestController
 public  class HelloController {
    
    @Autowired
    HelloService helloService;
    
    @GetMapping(value = "/test", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String query() {
        return "hello";
    }
}

- The second way (recommended)

PS: There is a problem with the first one. When the server throws 500, there is still a cross-domain problem.

@SpringBootApplication
@ComponentScan
@EnableDiscoveryClient
public class ManagementApplication {

    public static void main(String[] args) {
        SpringApplication.run(ManagementApplication.class, args);
    }

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addExposedHeader(HttpHeaderConStant.X_TOTAL_COUNT);
        return corsConfiguration;
    }

    /**
     * Cross domain filter
     *
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
}

- index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Cross-Origin Request</title>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({url:"http://localhost:8080/test",success:function(result){
            $("#p1").html(result);
        }});
    });
});
</script>
</head>
<body>

<p width="500px" height="100px" id="p1"></p>
<button>Get other content</button>
</body>
</html>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324836894&siteId=291194637