对 Tomcat 服务器进行 API 调用时如何修复“被 CORS 策略阻止”错误

Posted

技术标签:

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

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

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

【问题讨论】:

【参考方案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。

    进行 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 才能使其工作。

希望对你有所帮助。

【讨论】:

以上是关于对 Tomcat 服务器进行 API 调用时如何修复“被 CORS 策略阻止”错误的主要内容,如果未能解决你的问题,请参考以下文章