ajax请求跨域
描述:
举个栗子:在A网站中,我们希望使用Ajax来获得B网站中的特定内容。如果A网站与B网站不在同一个域中,那么就出现了跨域访问问题。你可以理解为两个域名之间不能跨过域名来发送请求或者请求数据,否则就是不安全的。跨域访问违反了同源策略,同源策略的详细信息可以点击如下链接:Same-origin_policy;
总而言之,同源策略规定,浏览器的ajax只能访问跟它的HTML页面同源(相同域名或IP)的资源。
1.客户端解决
dataType: 'jsonp'
将ajax请求中的dataType属性设置为“jsonp”,jsonp是专门用来解决跨域访问而诞生的。
2.服务端解决(spring boot)
编写过滤器
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
配置过滤器
@Component
@Configuration
public class SpringMVCConfig extends WebMvcConfigurerAdapter {
/**
* 配置过滤器
* @return
*/
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(sessionFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("cORSFilter");
return registration;
}
/**
* 创建一个bean
* @return
*/
@Bean(name = "cORSFilter")
public Filter sessionFilter() {
return new CORSFilter();
}
}
此时请求就不会出现 Access-Control-Allow-Origin 跨域请求了。