javascriptjavareactjscorsfetch

Tryed to fetch and get error with CORS or empty response


The problem is that when requesting from the frontend to the server, it returns either an error or an empty string (just empty) to the console if you disable Cors in fetch(mode: "no-cors").
CORS headers are disabled on the server, which means they shouldn't be there, but to be safe, after I got an error, I also tried to configure CORS in fetch: I turned it off completely (mode:"no-cors"), prescribe the headers themselves.

At the same time, when I send a request without React - in pure JS or using Postman, the string is displayed correctly and the server responds without any problems.

Backend(Java):

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {

 public static void main(String[] args) {
  SpringApplication.run(DemoApplication.class, args);
 }

 @GetMapping
 public String hello() {
  return "hello";
 }
}

Frontend (JavaScript, React):

import { useEffect, useState } from "react";

function App() {
  const [response, setResponse] = useState("");

  useEffect(() => {
    fetch('http://localhost:8080')
      .then(response => response.text())
      .then(text => setResponse(text))
      .catch(error => console.error('Error:', error));
  }, []); 

  return (
    <div>
      {response}
    </div>
  );
}

export default App;

Solution

  • Your Spring Boot backend needs CORS configuration to explicitly allow requests from your React frontend. Here's how to fix it:

    1. Configure CORS in Spring Boot (Backend) Option 1: Global Configuration Add this configuration class to your Spring Boot application:
    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("/**")
                    .allowedOrigins("http://localhost:3000") // React dev server
                    .allowedMethods("*")
                    .allowedHeaders("*");
        }
    }
    

    Option 2: Controller Annotation Add @CrossOrigin to your controller method:

    @RestController
    public class DemoApplication {
        @GetMapping
        @CrossOrigin(origins = "http://localhost:3000")
        public String hello() {
            return "hello";
        }
    }
    
    1. Update Frontend Code (React) Remove mode: "no-cors" and use a standard fetch:
    useEffect(() => {
      fetch('http://localhost:8080')
        .then(response => {
          if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
          return response.text();
        })
        .then(text => setResponse(text))
        .catch(error => console.error('Fetch error:', error));
    }, []);
    

    This configuration allows your React app to communicate securely with the Spring Boot backend.