后端一般用cors解决跨域问题,需要配置下面的内容
1.允许任何域名使用,正式环境应该指定跨域访问的域名或ip
2.允许任何头
3.允许任何方法(post、get等)
ssm/jsp项目
通过编写一个过滤器【CorsFilter.java】以及配置【web.xml】来实现
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "PUT,POST, GET, OPTIONS, DELETE");
//推荐允许任何头,否则可能跨域无法解决!!!
response.setHeader("Access-Control-Allow-Headers","*")
filterChain.doFilter(servletRequest, servletResponse);
}
}
配置web.xml
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>com.sale4gr.filter.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
springboot项目
通过编写一个配置类【CorsConfig.java】来实现
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
/**
跨域问题的cors全局解决方案
*/
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用,正式环境应该指定跨域访问的域名或ip
corsConfiguration.addAllowedHeader("*"); // 2允许任何头
corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}