关于什么是跨域的问题,感兴趣的同学可以看阮一峰老师的日志 http://www.ruanyifeng.com/blog/2016/04/cors.html。
下面贴出我在springboot项目中的跨域配置。
1、CorsConfig
package com.example.demo; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址 corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头 corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法 return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置 return new CorsFilter(source); } }
2、CorsQusetionApplication
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class CorsQusetionApplication extends SpringBootServletInitializer{ @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(CorsQusetionApplication.class); } public static void main(String[] args) { SpringApplication.run(CorsQusetionApplication.class, args); } @GetMapping("/get") public Object getMethod() { return "Stirng"; } }
3、测试网页
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-1.7.2.min.js"></script> <script type="text/javascript"> function crosRequest(){ $.ajax({ url:‘http://localhost:8080/get‘, type:‘get‘, dataType:‘text‘, success:function(data){ alert(data); } }); } </script> </head> <body> <button onclick="crosRequest()">请求跨域资源</button> </body> </html>
pom文件添加上web启动包即可,启动项目,将测试网页test.html在电脑中任意位置放置,用浏览器打开,可以正常响应
注释掉cors配置,重新启动项目,将测试网页test.html在电脑中任意位置放置,用浏览器打开,打开开发工具,发现控制台报错
原文地址:https://www.cnblogs.com/hhhshct/p/9249964.html
时间: 2024-11-06 03:43:20