CORS with Quarkus - Example
Hello everyone, today we will show you how to enable CORS support in the Quarkus application at the global level.
CORS Error in Web Apps:
Let's learn how to enable cors in quarkus application,
Quarkus comes with a CORS filter that implements the javax.servlet.Filter interface and intercepts all incoming HTTP requests. It can be enabled in the Quarkus configuration file,
application.properties:
quarkus.http.cors=truequarkus.http.cors.origins=http://localhostquarkus.http.cors.methods=GET,PUT,POSTquarkus.http.cors.headers=X-Customquarkus.http.cors.exposed-headers=Content-Dispositionquarkus.http.cors.access-control-max-age=24Hquarkus.http.cors.access-control-allow-credentials=true
UserResource:
package com.knf.dev.demo;
import javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.Produces;import javax.ws.rs.core.MediaType;import javax.ws.rs.core.Response;
@Path("/api/users")public class UserResource {
@GET @Produces(MediaType.APPLICATION_JSON) public Response hello() { return Response.ok("Congratulations! CORS enabled"). build(); }}
Run:
Build application jar file: mvn clean package
Start the application: java -jar quarkus-run.jar
Calling the REST endpoint:
<!DOCTYPE html><html><body>
<div id="demo"><h1>CORS Demo</h1><button type="button" onclick="loadDoc()"> Back End Call</button></div>
<script>function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "http://localhost:8080/api/users/", true); xhttp.send();}</script></body></html>