我目前遇到了一个问题,在我的Vert.x应用程序中包含必要的CORS头。尽管尝试了this Stack Overflow post中提供的解决方案,但我仍无法成功地将头添加到响应中。当尝试从前端发送请求时,我收到以下错误消息:
Acess to XMLHttpRequest at 'http://localhost:8081/api' from origin 'http://localhost:4287' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我的HttpServerVerticle类中的相关代码片段如下:
> public class HttpServerVerticle extends AbstractVerticle {
@Override
public void start(Promise<Void> startPromise) {
ApiServiceApiHandler apiHandler = new ApiServiceApiHandler(new ApiServiceApiImpl());
RouterBuilder.create(vertx, specFile)
.map(builder -> {
builder.setOptions(
new RouterBuilderOptions()
// For production use case, you need to enable this flag and provide the
// proper security handler
.setRequireSecurityHandlers(false));
vertx.eventBus().registerDefaultCodec(DBUserRequest.class, new LocalEventBusCodec<>(DBUserRequest.class));
vertx.eventBus().registerDefaultCodec(ArrayList.class, new LocalEventBusCodec<>(ArrayList.class));
apiHandler.mount(builder);
Router router = builder.createRouter();
router.route().handler(CorsHandler.create("http://localhost:4287")
.allowedMethod(io.vertx.core.http.HttpMethod.GET)
.allowedMethod(io.vertx.core.http.HttpMethod.POST)
.allowedMethod(io.vertx.core.http.HttpMethod.OPTIONS)
.allowCredentials(true)
.allowedHeader("Access-Control-Allow-Method")
.allowedHeader("Access-Control-Allow-Origin")
.allowedHeader("Access-Control-Allow-Credentials")
.allowedHeader("Content-Type"));
router.errorHandler(400, new ExceptionHandler());
router.errorHandler(405, new ExceptionHandler());
router.errorHandler(404, new ExceptionHandler());
return router;
})
.compose(router->vertx.createHttpServer(options).requestHandler(router).listen(Vertx.currentContext().config().getInteger(ConfigConstants.PROPERTY_SERVICE_HTTP_PORT));
.onSuccess(server -> logger.info("Http verticle deploy successful"))
我将非常感谢任何指导或建议,以解决上述CORS问题。
我已经尝试了这个链接中提到的解决方案-CORS issue in vertx Application not working
我也试过将原点改为“.*.”,但结果是一样的。
1条答案
按热度按时间oxf4rvwz1#
当您使用
RouterBuidler
for OpenAPI创建Router
时,已经定义了路由。因此,如果您为
CorsHandler
定义了路由,它将作为最后一个路由定义安装。在这种情况下,您可以先添加
CorsHandler
路由,然后将Router
作为子路由器挂载到OpenAPI: