What steps can be taken to resolve the issue of CORS in react spring boot integration?

I have implemented a CORS filter class in my Spring Boot application:

@Component
public class CorsingFilter {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // It's important not to do this in production, use a proper list of allowed origins
        config.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
        config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

Here is the controller I have defined:

@RestController
@RequestMapping("/test")
public class TestController {

    @CrossOrigin(origins = "http://localhost:3000")
    @GetMapping("/cox")
    public String getCox(){
        return "COX";
    }
}

This is the react request I am making:

let url = "http://localhost:8080/test/cox";
    const agent = new https.Agent({
      rejectUnauthorized: false
    });
    try {
      const res = await axios.get(url, {
        auth: {
          username: 'user',
          password: '123456'
        },
        headers: {
          'Content-Type': 'application/json',
          "Access-Control-Allow-Origin": "http://localhost:8080",
          'Access-Control-Allow-Credentials': true,
          "Access-Control-Allow-Methods": 'HEAD, GET, POST, PUT, PATCH, DELETE',
          "Access-Control-Allow-Headers": 'Origin, Content-Type, X-Auth-Token',
        },
        httpsAgent: agent
      })
      console.log(res)
    } catch (err) {
      console.log(err)
    }

This is how the browser cors error appears
This is what the request looks like

In addition, the request successfully works when accessed from the browser (using localhost:8080)

Answer №1

Key Points

  1. The React application is generated using the create-react-app command.
  2. In a production environment, both the front-end and back-end will share the same server.

Solution Steps

  1. Include
    "proxy": "http://localhost:8080"
    in the package.json file of the React application.
  2. Edit the URL to be /test/cox.

Read more about proxying API requests during development.

It's worth mentioning that frameworks like Gatsby and Next.js also have a similar feature, typically referred to as the "proxy" setting.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React App's proxy configuration to connect with an Express server for PassportJS authentication is currently malfunctioning

After spending some time trying to configure a proxy for my React app to connect with my Express backend, using passportjs for Google social authentication, I encountered an issue. The React development server is running on PORT 3000 while the Express ser ...

When I incorporate a query, the value for this.props.location becomes undefined

Is there a way to add a query parameter like mobile=true to the URL in order to access a slightly modified page? I have successfully implemented this in App.js using the code const mobileAp = location.search.indexOf("mobile=true") > -1;. However, when I ...

In ReactJs, what is the best way to load a new component when a button is clicked?

In ReactJs, I have developed a main component known as MainPage using Material-UI. import React from 'react'; import Grid from '@material-ui/core/Grid'; import Button from '@material-ui/core/Button'; import CssBaseline from & ...

Choosing the Perfect Title for Your MUI X Data Grid

I'm currently experimenting with the MUI X Data Grid React Component, which is licensed under MIT. Is there a way to include a title above the column headers but below the border of the Data Grid? I'd prefer simple centered text or even custom c ...

"Troublesome issue: React.memo fails to prevent re-rendering of nested

I am currently working on a React Native messenger application and I have structured my Redux store like this: https://i.stack.imgur.com/6g8hw.png Here is the component that renders: https://i.stack.imgur.com/b3UwG.png My issue is that every time an ev ...

I am having trouble scrolling through the main content when the side-drawer is open. How can I fix this issue?

When the sidebar is opened, I am facing issues with the main content scroll and certain fields such as select options and search bar not functioning properly. I have included the main content in the routes from which it is being loaded. However, the scroll ...

What methods can I use to minimize the duration of invoking the location.reload() function?

When I'm using window.location.reload() in my onClick() function, it's taking too long to reload. I tried modifying the reload call to window.location.reload(true) to prevent caching, but it's still slow. The issue seems to be with location. ...

Set the GridToolbarQuickFilter text box to have an outlined style in Material UI v5

How can I customize the appearance of the GridToolbarQuickFilter textbox, such as outlining it? Ideally, I would like to accomplish this through theme.tsx, but I am open to any suggestions. https://i.stack.imgur.com/H1Ojj.png I have experimented with var ...

Fixing compatibility problems, security risks, alerts, clashes, and disparate releases within React

I am currently working on: Resolving the dependency issues that are surfacing in my React application Gaining a deeper understanding of why these issues are occurring Finding the best approach to address these types of problems properly, without resorting ...

Utilizing the componentDidUpdate method to update the state within the component

I have a scenario where two components are enclosed in a container. One component is retrieving the Id of a publication, while the other is fetching the issue date related to that specific publicationId. When I retrieve an Id, let’s say 100, it successf ...

What is the proper way to invoke a function that is part of a child component as a property in a React application?

In my app.js file, I have included a unique component called "SigningComponent" with the following code: onSign = () => { this.setState({ route: "home" }); }; registerFunction = () => { this.setState({ route: "registration" }); }; render() { ...

Is it possible to configure React JS and React Native together within a single project?

I'm looking to incorporate both React JS for web and React Native for mobile within the same project, utilizing redux and stylesheet. While exploring various repositories like ReactNativeWebHelloWorld, I encountered issues due to outdated versions th ...

Utilize the Material UI SelectField component as a reference for handling onChange events

I'm facing a challenge with my form that contains over 15 SelectField components. I want to avoid creating multiple change handler functions, but I can't figure out how to identify the specific select field that triggered the change event in orde ...

Curious about how to utilize Gridfs to upload files or videos larger than 16mb with the help of express, mongoose, and mongodb?

I'm encountering an issue with my code. It works fine for uploading images, but when I try to upload videos or files larger than 16mb, it fails. I am a beginner and seeking help on what to do next. const Freecoursevideo = require("../models/freec ...

The React Native File generator

Currently, we are utilizing redux actions in our web project. In an effort to share logic between web and native applications, we have integrated these actions into our react native project with the intention of only having to modify the components. One o ...

The variable "drupalSettings" is not defined and is causing an error "no-undef"

I am working on a single page app that needs to run within every Drupal node of a specific content type. This app is built using React and Yarn. Within my index.js file, I have the following code snippet: if(window.location.href !== 'http://localho ...

Unable to preserve the value of react material-ui autoCompletion using formik

Greetings everyone! Today, I wanted to address an issue that has been causing some trouble for me recently. I've been utilizing the autoCompletion feature from materiall-ui along with formik in reactjs. However, I've been facing difficulties when ...

Issue with Chrome not triggering onMouseEnter event when an element blocking the cursor disappears in React

Important Note: This issue seems to be specific to Chrome Currently, React does not trigger the onMouseEnter event when a blocking element disappears. This behavior is different from standard JavaScript events and even delegated events. Below is a simpli ...

Steps to implement the selection of multiple items from a drop-down or list on a React.js website

Hi there, I am a newcomer to the world of React JS web development. I am looking for guidance on how to implement a feature where users can select multiple cities from a drop-down or list, similar to the examples shown in image1. Once the user has made th ...

Exploring ways to bypass authentication using react development tools

Currently, I am delving into the realm of token-based authentication in SPA and a question has been nagging at me. Picture this: in my app, the authentication process works like this - when a user enters correct credentials, they receive a token and the "a ...