解决Java后台接口跨域,nginx跨域配置。
2种常用解决跨域方法:
1、nginx配置
在nginx.conf 配置的location 节点下加入如下配置信息:
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers “Origin, X-Requested-With, Content-Type, Accept”;
add_header Access-Control-Allow-Methods “GET, POST, OPTIONS”;
2、springboot注解配置
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 {
/** * 设置 - 限定访问源 * @return */
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
return corsConfiguration;
}
/** * 设置接口地址 * @return */
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
还没有评论,来说两句吧...