React 应用中通过 Axios 向后端发送数据时的 CORS 问题

问题描述 投票:0回答:1

从源“http://localhost:5173”访问“http://localhost:8080/api/submitForm”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否“ Access-Control-Allow-Origin' 标头存在于请求的资源上。

我在 github 上的完整后端https://github.com/JadhavC07/back-end 和我的前端https://github.com/JadhavC07/Student-Form

这是我的 Spring Boot 后端中的 CORS 配置类:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

这是我在 React 组件中进行 API 调用的方式:

import axios from 'axios';

const baseURL = "http://localhost:8080/api";

const sendDataToBackend = (data) => {
    axios
      .post(`${baseURL}/submitForm`, data)
      .then((response) => {
        console.log("Data sent successfully", response.data);
        // Additional logic
      })
      .catch((error) => {
        console.error("Error sending data to the backend", error);
        // Error handling logic
      });
};

我已将后端配置为允许所有来源和方法,包括 POST,理论上这应该可以解决 CORS 问题。但是,我仍然遇到该错误。任何有关如何解决此问题的见解将不胜感激。谢谢!

我更新了 Spring Boot 后端中的 CORS 配置,以允许所有来源和方法,包括 POST 请求。我希望此配置能够解决 CORS 问题,并允许我的 React 应用程序成功将数据发送到后端 API,而不会遇到 CORS 错误。然而,尽管进行了这些更改,CORS 错误仍然存在,并且我仍然无法将数据发送到后端。

java spring api cors
1个回答
0
投票

这是因为我没有在React中设置代理。 请告诉我们您正在使用哪个框架, 无论是next js还是reactNative, 我们将向您展示如何相应地设置代理。

© www.soinside.com 2019 - 2024. All rights reserved.