"No 'Access-Control-Allow-Origin' header"跨域问题CROS

问题描述

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access.

浏览器跨域测试

  • 直接使用浏览器开发者工具, 在控制台执行代码测试
// 正常情况
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/test.pdf');
xhr.send(null);
xhr.onload = function(e) {
    var xhr = e.target;
    console.error(xhr.responseText);
}

// 跨域
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:8080/themes/zone/casepdf/177.pdf');
xhr.send(null);
xhr.onload = function(e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}

Tomcat 跨域配置

web.xml

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Spring跨域配置

https://www.cnblogs.com/52liming/p/9535636.html

参考博客

Spring MVC通过CROS协议解决跨域问题

作者原文链接:http://www.imooc.com/article/7719

spring 官方文档:

链接:https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-cors

原文地址:https://www.cnblogs.com/52liming/p/8484123.html