javareactjscors

React + Spring Boot: Getting CORS error while making get-request to server


I'm encountering a CORS issue when sending a GET request from my frontend to 'http://localhost:8080/api/projects/admin/toinspection'. The error message is:

“Access to XMLHttpRequest at 'http://localhost:8080/api/projects/admin/toinspection' from origin 'http://localhost:8081' has been blocked by CORS policy: The response to the preflight request doesn't pass the access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.”

CORS is configured correctly, and the request works fine in Postman. What could be the cause of the issue in the browser?

Thank you in advance for your help.

There is my components snippets:

// ProjectPage.tsx

const ProjectsPage = () => {

    const [projectsData, setProjectsData] = useState<ProjectsData[]>([])
    const projectsUrl = 'http://localhost:8080/api/projects/admin/toinspection'


    useEffect(() => {
        fetchData().then(r => console.log(r))
    }, []);

    const fetchData = async() => {
            const token = Cookies.get('token')
            const response = await axios.get<ProjectsData[]>(projectsUrl, {
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`,
                },
                withCredentials: true
            })
            setProjectsData(response.data)
        }

    return (
        <div>
            <AdminPageTemplate type="projects" children={<AdminModContent data={projectsData}/>}/>
        </div>
    );
};

export default ProjectsPage;

// AdminModContent.tsx

const AdminModContent: React.FC<ModeratorContentProps> = ({ data }) => {
    if (!data || data.length === 0) {
        return (
            <div className={styles.adminModContact__empty}>
                No content to moderate
            </div>
        );
    }

    const renderContent = (item: ContentItem) => {
        if (!item) return null;

        switch (item.type) {
            case "projects":
                return (
                    <div key={item.id} className={styles.adminModContact__projects}>
                        <p>ID: {item.id}</p>
                        <h3>Project: {item.title}</h3>
                        <p>Tech Stack: {item.technologyStack}</p>
                        <p>Description: {item.mainText}</p>
                        <p>Wishes: {item.wishes}</p>
                        <div className={styles.adminModContact__actions}>

                        </div>
                    </div>
                );
    };

    return (
        <div className={styles.adminModContact}>
            {data.map(item => renderContent(item))}
        </div>
    );
};

export default AdminModContent;

// CorsConfig.java

@Bean
    public WebMvcConfigurer getWebMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://localhost:8081")
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                        .allowedHeaders("*")
                        .allowCredentials(true);
            }
        };
    }

Solution

  • As mentioned in the comments, if you use spring security you should also enable cors on your securityfilterchain bean.

    @EnableWebSecurity
    public class WebSecurityConfig {
        @Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            return http
                .cors()
                .and()
                ...
                .build()
        }
    }