Search code examples
javascriptspring-bootcorsspring-cloud-gateway

Multiple CORS header 'Access-Control-Allow-Origin' not allowed | Spring Boot


I am getting following error when I tried to fetch data from the Spring Boot Backend with HTML + JS

Access to fetch at 'http://localhost:8222/api/v1/admin/hotels?page=0&size=10&searchText=&petAllowed=true&starRate=2&priceLow=1&priceHigh=10001' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I am using Spring Cloud Gateway to route the traffic.

Yaml file in the gateway

spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      globalcors:
        cors-configurations:
            '[/**]':
                allowedOrigins: "*"
                allowedMethods:
                - GET
                - POST
                - PUT
                - DELETE
                - OPTIONS
                allowedHeaders:
                - "*"

I am using JS to fetch the data.

fetch(
  "http://localhost:8222/api/v1/admin/hotels?page=0&size=10&searchText=&petAllowed=true&starRate=2&priceLow=1&priceHigh=10001",
  {
    method: "GET",
    mode: "cors",
  }
)
  .then((response) => response.json())

What I am doing wrong here?


Solution

  • May the issue be in the code. Check the code for the duplicate Cors handling. Ex: You handle the cors in the yaml file mentioned and maybe you write a code in the controller. Like

    @RestController
    @RequestMapping("api/v1/admin/hotels")
    @CrossOrigin("*")
    public class HotelController {}
    

    Most probably it might be the issue. If you have that remove that CrossOrigin line and restart servers.

    If the issue persists consider trying another browser or if you are using Chrome, use the This Extension. This might break the other sites, use with only testing the code.