【问题标题】:How to fix the "blocked by CORS policy" error when making a API call to Tomcat server对 Tomcat 服务器进行 API 调用时如何修复“被 CORS 策略阻止”错误
【发布时间】:2020-01-14 21:53:12
【问题描述】:

当我尝试使用 axios 对 Tomcat 8 服务器进行 API 调用时出现以下错误。

被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头 出现在请求的资源上。

【问题讨论】:

    标签: cors axios tomcat8


    【解决方案1】:
    1. 打开您打算启用 CORS 并添加 CORS 过滤器声明和映射的 Web 应用程序的 $CATALINA_HOME/webapps/<your-web-app>/WEB-INF/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>
      

      *重要提示:出于安全原因,将 &lt;param-value&gt;*&lt;/param-value&gt; 更改为仅允许您的网站而不是 *

    您可能需要添加其他&lt;init-param&gt;。例如,您需要添加cors.allowed.headers 以接受您的自定义标头,例如token。 有关初始化参数的更多信息,请阅读tomcat document

    1. 进行 API 调用。

      axios
      .post('http://path/to/api'
      , {xhrFields: {withCredentials: true},
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
      

    我花了好几个小时才弄清楚我必须拥有{xhrFields: {withCredentials: true} 才能使其工作。

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-04-14
      • 2021-06-22
      • 2021-04-08
      • 1970-01-01
      • 2019-10-31
      • 2020-09-13
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多