CORS
全称为Cross Origin Resource Sharing
(跨域资源共享), 每一个页面需要返回一个名为Access-Control-Allow-Origin
的http头来允许外域的站点访问,你可以仅仅暴露有限的资源和有限的外域站点访问。
如果一个请求需要允许跨域访问,则需要在http头中设置Access-Control-Allow-Origin来决定需要允许哪些站点来访问。如假设需要允许https://www.xxx.com这个站点的请求跨域,则可以设置:
Access-Control-Allow-Origin:https://www.xxx.com
- 使用
@CrossOrigin
注解
在Controller
上使用@CrossOrigin
注解,该类下的所有接口都可以通过跨域访问
@RequestMapping("/api")
@RestController
@CrossOrigin("https://www.xxx.com") //只有指定域名可以访问该类下所有接口
public class CorsTestController {
@GetMapping("/sayHello")
public String sayHello() {
return "hello world";
}
}
CORS
全局配置-实现WebMvcConfigurer
新建跨域配置类:CorsConfig.java
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 跨域配置
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer corsConfigurer()
{
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").
allowedOrigins("https://www.xxx.com"). //允许跨域的域名,可以用*表示允许任何域名使用
allowedMethods("*"). //允许任何方法(post、get等)
allowedHeaders("*"). //允许任何请求头
allowCredentials(true). //带上cookie信息
exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
}
};
}
}