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:


Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

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=true
quarkus.http.cors.origins=http://localhost
quarkus.http.cors.methods=GET,PUT,POST
quarkus.http.cors.headers=X-Custom
quarkus.http.cors.exposed-headers=Content-Disposition
quarkus.http.cors.access-control-max-age=24H
quarkus.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>

Popular posts from this blog

Spring boot video streaming example-HTML5

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example