首页 > 解决方案 > CORS 策略已阻止访问 fetch。它没有 HTTP ok 状态

问题描述

所以我正在构建一个反应应用程序,它从我构建的 spring boot rest api 中获取 JSON 数据。

下面是 fetch 方法的代码:

componentDidMount() {
        fetch(`http://localhost:8080/students`, {
            headers : {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }

        })
            .then((response) => response.json())
            .then((data) => this.setState({students: data}));

        console.log(this.state.students);
    }

但是,当我运行该程序时,它给了我一个错误消息:

Access to fetch at 'http://localhost:8080/students' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

谁能帮我?

标签: spring-bootfetch

解决方案


我对 Spring Boot 不是 100% 熟悉,但这个问题的一般解决方案是确保您的服务响应与源匹配的 Access-Control-Allow-Origin 标头(在您的示例中为 localhost),如果它不是与您的服务相同的来源。

添加"Access-Control-Allow-Origin": "*"会为您的开发目的而做。在生产中,您可能希望更具体地说明实际允许的来源。

查看此资源以获取有关 CORS 的更多信息:https ://enable-cors.org/

这是在您的浏览器中实施的相同来源策略导致了这种情况。它指定浏览器应该允许一个网页中的脚本访问另一个网页上的资源,但前提是它们来自同一来源。如果它们不是,您可以通过指定我上面提到的标头来指定它们是允许的。您可能还需要指定允许的动词和标题,具体取决于您在做什么。


推荐阅读