最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Tryed to fetch and get error with CORS or empty response - Stack Overflow

programmeradmin1浏览0评论

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 .springframework.boot.SpringApplication;
import .springframework.boot.autoconfigure.SpringBootApplication;
import .springframework.web.bind.annotation.GetMapping;
import .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;

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 .springframework.boot.SpringApplication;
import .springframework.boot.autoconfigure.SpringBootApplication;
import .springframework.web.bind.annotation.GetMapping;
import .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;
Share Improve this question asked Mar 3 at 16:34 ii5ii5 212 bronze badges 2
  • 'or an empty string (just empty) to the console if you disable Cors in fetch(mode: "no-cors")' - that is exactly the intended behavior, when you set no-cors. – C3roe Commented Mar 4 at 8:50
  • "when I send a request without React - in pure JS or using Postman, the string is displayed correctly" - CORS restrictions do not apply to tools like Postman. And what do you mean when you say "in pure JS"? Show relevant code, please. – C3roe Commented Mar 4 at 8:51
Add a comment  | 

1 Answer 1

Reset to default 0

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 .springframework.context.annotation.Configuration;
import .springframework.web.servlet.config.annotation.CorsRegistry;
import .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.

发布评论

评论列表(0)

  1. 暂无评论