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

时间:2019-09-13 02:19:23

标签: cors axios tomcat8

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

  

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

1 个答案:

答案 0 :(得分:0)

  1. 打开您打算启用CORS的Web应用程序的$CATALINA_HOME/webapps/<your-web-app>/WEB-INF/web.xml文件,并添加CORS过滤器声明和映射。

      <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>
    

    *重要:出于安全原因,将<param-value>*</param-value>更改为仅允许您的网站而不是*

您可能需要添加其他<init-param>。例如,您需要添加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}才能使其正常工作。

希望它对您有帮助。