我试图添加一个CORS过滤器到Jetty服务器(使用Jetty 11.0.14),以允许从其他域使用头,但我得到了一些错误。
当我提出请求时
from origin 'null' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'null, *', but only one is allowed.
我有一个简单的Jetty服务器进行测试,以重现我的问题
import org.eclipse.jetty.util.thread.*;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.servlet.*;
import org.eclipse.jetty.servlets.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;
public class WebServerUtil {
public static void main(String[] args) {
try {
// setup server
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setName("server");
Server server = new Server(threadPool);
// setup server connections
HttpConfiguration config = new HttpConfiguration();
HttpConnectionFactory httpConnection = new HttpConnectionFactory(config);
ServerConnector connector = new ServerConnector(server, httpConnection);
connector.setHost("0.0.0.0");
connector.setPort(8080);
server.setConnectors(new Connector[] { connector });
// setup handler
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
// setup cors
FilterHolder filter = new FilterHolder(CrossOriginFilter.class);
filter.setName("CORS");
filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
filter.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "*");
filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "POST, GET, OPTIONS");
FilterMapping mapping = new FilterMapping();
mapping.setFilterName("CORS");
mapping.setPathSpecs(new String[] {"/*"});
mapping.setDispatches(FilterMapping.ALL);
handler.addFilter(filter, mapping);
// basic route
ServletHolder nothing = new ServletHolder(new Nothing());
handler.addServletWithMapping(nothing, "/");
// start server
server.start();
server.join();
} catch(Exception error) {
System.out.println(error.getMessage());
}
}
}
class Nothing extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setStatus(200);
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Headers", "*");
res.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
res.addHeader("Content-Type", "application/json");
res.getWriter().println("{\"message\":\"Nothing\"}");
}
}
如果我删除设置cors位下的handler.addFilter(filter, mapping);
行,它可以工作,但只有在发出没有标题的请求时才能工作。
1条答案
按热度按时间6za6bjd01#
捕获触发此故障的HTTP请求,注意所有
Origin
头(和所有值)。从服务器上的错误来看,它似乎收到了多个
Origin
头,其中一个为空/null(或具有字符串null
),另一个为值*