Java CORS Error

Last Updated : 14 Oct 2026

Web browsers prevent websites from making requests to a domain other than the one that hosted the original website by utilizing a security feature known as CORS (Cross-Origin Resource Sharing). By limiting web apps to only interact with resources from their origin unless specifically permitted by the server, this security feature safeguards users.

A CORS issue is frequently seen when a Java program (such as a Spring Boot API) communicates with front-end clients (Angular, React, etc.) if the front-end and back-end are hosted on separate domains or ports.

What is a CORS Error?

A CORS error occurs when a web browser blocks a request to a server due to security policies. The browser expects specific CORS headers in the server's response to determine whether the request is allowed. A common example of a CORS error might look like this: CORS in Operation.

Handling CORS in Java Applications

In Java-based web applications (such as those using Spring Boot), developers can configure CORS support to avoid these errors. One of the most straightforward ways to handle CORS in Spring Boot is by using the @CrossOrigin annotation or by defining a CORS configuration globally.

1. Using @CrossOrigin Annotation

The @CrossOrigin annotation can be applied to controllers or specific endpoints to specify which origins are allowed to access them.

2. Global CORS Configuration

Alternatively, you can configure CORS globally for the entire Spring Boot application by defining a WebMvcConfigurer bean.

Common Mistakes in Java CORS

  1. Wildcard Using Certifications: A wildcard (*) in the Access-Control-Allow-Origin header will prevent CORS requests containing credentials (such as cookies or HTTP authentication) from succeeding. Particular origins ought to be used when credentials are concerned.
  2. Absence of Preflight Support: The browser will issue a preflight request if your application sends PUT or DELETE requests. Make that the server sends the proper CORS headers in response to the HTTP OPTIONS method.
  3. Incorrect Headers: Verify that the request's Access-Control-Allow-Headers has all required custom headers.

Examples of Java CORS Error

The following examples demonstrate common CORS errors in Java web applications and how to resolve them using Spring Boot. These examples cover missing CORS configuration, the @CrossOrigin annotation, and global CORS configuration.

Example 1: CORS Error Due to Missing Configuration

In the following example, a Spring Boot API does not define CORS permissions for a frontend application running on a different port. When the browser sends a cross-origin request, it blocks access to the response if the server does not return the required CORS headers.

FileName: CorsController.java

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CorsController {

    @GetMapping("/api/message")
    public String getMessage() {
        return "Hello from Spring Boot API!";
    }
}

Suppose the Spring Boot application runs at http://localhost:8080, and the frontend runs at http://localhost:3000.

The frontend sends the following JavaScript request:

fetch("http://localhost:8080/api/message")
    .then(response => response.text())
    .then(data => console.log(data))
    .catch(error => console.error(error));

Example Error:

Access to fetch at 'http://localhost:8080/api/message'

from origin 'http://localhost:3000' has been blocked by CORS policy:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

Solution:

Add the @CrossOrigin annotation to the controller or endpoint to allow requests from the frontend origin.

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class CorsController {

    @GetMapping("/api/message")
    public String getMessage() {
        return "Hello from Spring Boot API!";
    }
}

After this configuration, the browser can access the endpoint from http://localhost:3000, provided no other security or server configuration blocks the request.

Example 2: Resolving a CORS Error Using @CrossOrigin

In this example, a Spring Boot application exposes a REST endpoint that should be accessible to a frontend application hosted on another origin. The @CrossOrigin annotation specifies the permitted origin and HTTP methods.

FileName: ProductController.java

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/products")
@CrossOrigin(
    origins = "http://localhost:3000",
    methods = {
        org.springframework.web.bind.annotation.RequestMethod.GET,
        org.springframework.web.bind.annotation.RequestMethod.POST
    }
)
public class ProductController {

    @GetMapping
    public String getProducts() {
        return "Product list";
    }

    @PostMapping
    public String addProduct(@RequestBody String product) {
        return "Product added: " + product;
    }
}

The frontend can send a GET request to retrieve products:

fetch("http://localhost:8080/api/products")
    .then(response => response.text())
    .then(data => console.log(data));

Output:

Product list

The frontend can also send a POST request with product data:

fetch("http://localhost:8080/api/products", {
    method: "POST",
    headers: {
        "Content-Type": "text/plain"
    },
    body: "Laptop"
})
    .then(response => response.text())
    .then(data => console.log(data));

Output:

Product added: Laptop

The @CrossOrigin annotation configures CORS for the controller's endpoints. For this example, the frontend must use the specified origin, and the server must accept the requested HTTP method and headers.

Example 3: Resolving CORS Errors Using Global Configuration

In this example, a Spring Boot application uses global CORS configuration to allow requests from a frontend application. This approach is useful when multiple controllers need the same CORS settings.

FileName: CorsConfig.java

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("Content-Type", "Authorization");
    }
}

Create a REST controller to provide an API endpoint.

FileName: MessageController.java

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MessageController {

    @GetMapping("/api/message")
    public String getMessage() {
        return "CORS configured globally!";
    }
}

The frontend sends a request to http://localhost:8080/api/message.

Output:

CORS configured globally!

The global configuration applies to URLs matching /api/**. It permits requests from http://localhost:3000 using the configured HTTP methods and request headers.

Note: If the application uses Spring Security, its security configuration must also support CORS. For requests containing cookies or other credentials, configure specific trusted origins and credentials explicitly; do not combine credentialed CORS requests with a wildcard origin.