React + Spring Boot:向服务器发出 get 请求时出现 CORS 错误

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

从前端发送 GET 请求到 'http://localhost:8080/api/projects/admin/toinspection'。错误信息是:

“从源“http://localhost:8081”访问“http://localhost:8080/api/projects/admin/toinspection”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应不会通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。”

CORS配置正确,请求在Postman中工作正常。浏览器中出现问题的原因可能是什么?

提前感谢您的帮助。

这是我的组件片段:

// 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);
            }
        };
    }
java reactjs cors
1个回答
0
投票

导入org.springframework.context.annotation.Bean; 导入 org.springframework.security.config.annotation.web.builders.HttpSecurity; 导入 org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 导入 org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity 公共类 WebSecurityConfig {

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

}

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