跨域
跨域问题的产生
由于请求头缺少信息违反了同源策略,所以被 CORS 策略拦截
Access to XMLHttpRequest at '<http://localhost:8081/user/userInfo?username=&password=>' from origin '<http://localhost:8080>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
CORS
全称:Cross Origin Resource Sharing(跨域资源共享)
基于 HTTP 头的机制,该机制通过允许服务器标示除了它自己以外的其它源(域、协议和端口),使得浏览器允许这些 origin 访问加载自己的资源。跨源资源共享还通过一种机制来检查服务器是否会允许要发送的真实请求,该机制通过浏览器发起一个到服务器托管的跨源资源的"预检"请求。在预检中,浏览器发送的头中标示有 HTTP 方法和真实请求中会用到的头。
同源策略
同源策略是浏览器的保护机制
要求:协议、域名、端口都相同就是同源
环境
- Vue:http://localhost:8080
- Spring Boot:http://localhost:8081
由于 Vue 的端口和 Spring Boot 的端口不同,所以发生了跨域问题
解决方式
- SpringBoot 解决跨域三种方案
- 在目标方法上添加 @CrossOrigin 注解(适用于少量方法)
@GetMapping("/userInfo")
@CrossOrigin public void userInfo(HttpServletRequest request, HttpServletResponse response)
{ 省略..... }
- 添加 CORS 过滤器
package com.study.config;
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;
/** * CorsConfig 类 :
* @author Administrator */
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");//配置允许的请求
corsConfiguration.addAllowedHeader("*");//配置允许的请求头
corsConfiguration.addAllowedMethod("*");//配置允许的方法
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
- 实现WebMvcConfigure接口,重写addCorsMappings方法
package com.study.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/** * CorsWebConfjig 类 : * @author Administrator */
@Configuration
public class CorsWebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET","POST","DELETE","HEAD","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}