1. GlobalCorsConfig
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author yaoyuan2 * @date 2021-01-13 */ @Configuration public class GlobalCorsConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") //添加映射路径,“/**”表示对所有的路径实行全局跨域访问权限的设置 .allowedOrigins("*") //开放哪些ip、端口、域名的访问权限 .allowCredentials(true) //是否允许发送Cookie信息 .allowedMethods("GET","POST", "PUT", "DELETE") //开放哪些Http方法,允许跨域访问 .allowedHeaders("*") //允许HTTP请求中的携带哪些Header信息 .exposedHeaders("Accept","Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified"); //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息) } }; } }
2. index.html,别放到项目里,直接本地电脑打开
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <input type="button" value="跨域测试" onclick="btn();" /> <script > function btn() { axios.get('http://localhost:8080/?name=遥远4').then(function(response) { alert(response); }); } </script> </body> </html>