【发布时间】:2020-01-14 21:53:12
【问题描述】:
当我尝试使用 axios 对 Tomcat 8 服务器进行 API 调用时出现以下错误。
被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头 出现在请求的资源上。
【问题讨论】:
当我尝试使用 axios 对 Tomcat 8 服务器进行 API 调用时出现以下错误。
被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头 出现在请求的资源上。
【问题讨论】:
打开您打算启用 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>
*重要提示:出于安全原因,将 <param-value>*</param-value> 更改为仅允许您的网站而不是 *。
您可能需要添加其他<init-param>。例如,您需要添加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} 才能使其工作。
希望对你有所帮助。
【讨论】: