码头跨源过滤器

2022-09-01 07:37:03

我已经配置了Jetty的跨源过滤器,但我继续收到以下错误。有谁知道什么是错的以及如何解决它?错误消息下方是我的覆盖描述符(即补充web.xml)

错误:

Origin http://localhost:8090 is not allowed by Access-Control-Allow-Origin.

覆盖描述符:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
 <filter>
   <filter-name>cross-origin</filter-name>
   <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
   <init-param>
       <param-name>allowedOrigins</param-name>
       <param-value>*</param-value>
   </init-param>
   <init-param>
       <param-name>allowedMethods</param-name>
       <param-value>*</param-value>
   </init-param>
   <init-param>
       <param-name>allowedHeaders</param-name>
       <param-value>*</param-value>
   </init-param>
 </filter>
 <filter-mapping>
     <filter-name>cross-origin</filter-name>
     <filter-pattern>/*</filter-pattern>
 </filter-mapping>
</web-app>

请求标头

Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:Origin, Content-Type, Accept
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:8090
Referer:http://localhost:8090/home
User-Agent:Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.942.0

响应标头

Allow:POST,GET,OPTIONS,HEAD
Content-Length:0
Date:Wed, 30 Nov 2011 02:13:21 GMT
Server:Jetty(7.5.4.v20111024)

答案 1

阿罗哈

我也为此斗争了一段时间,发现最终节点需要是:

<filter-mapping>
    <filter-name>cross-origin</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
     <filter-name>cross-origin</filter-name>
     <filter-pattern>/*</filter-pattern>
</filter-mapping>

以下是我发现的帮助我的链接:wiki.eclipse.org/Jetty/Feature/Cross_Origin_Filter

在我更新了web.xml文件并重新启动了码头服务器之后,我能够使用jQuery ajax调用进行跨域请求。


答案 2

我在对部署到 GAE 的 Web 应用进行跨域调用时遇到了这种情况。您可以向 Servlet 响应添加显式标头,例如:

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException 
{
    res.addHeader("Access-Control-Allow-Origin", "*");
    ...
}

还要确保在 WAR 的根目录中有一个跨域.xml策略文件,例如:

<cross-domain-policy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="http://www.adobe.com/xml/schemas/PolicyFile.xsd">
<allow-access-from domain="*"/>
</cross-domain-policy> 

呵呵。


推荐