I'm currently experiencing an issue with including the necessary CORS headers in my Vert.x application. Despite trying the solutions provided in this Stack Overflow post, I haven't been able to successfully add the headers to the response. When attempting to send a request from my frontend, I receive the following error message:
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.
The relevant code snippet from my HttpServerVerticle class is as follows:
> 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"))
I would greatly appreciate any guidance or suggestions to resolve the CORS issue mentioned above.
I have already tried the solution mentioned in this link - CORS issue in vertx Application not working
Also I tried by changing the origin to ".*." but the result was the same.