javascript - 努力从 fetch api 获取数据以获取对 http ://swapi. co 的请求

标签 javascript cors fetch

我正在努力向 http://swapi.co.in 发出成功的请求来 self 的本地主机 creat-react-app 项目。 我已将 fetch api 请求放入主容器的 componentDidMount 中。

fetchData = () => {
        return fetch('http://swapi.co/api/people', {method: 'GET'}).then((response) => {
            console.log(response);
        });
    }

    componentDidMount() {
        this.fetchData();
    }

给我一​​个错误

Failed to load http://swapi.co/api/people: Redirect from 'http://swapi.co/api/people' to 'https://swapi.co/api/people' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


1 Uncaught (in promise) TypeError: Failed to fetch

在我将 fecth 数据函数更新为

 fetchData = () => {
        return fetch('http://swapi.co/api/people', {
            method: 'GET',
            headers: {
                'Access-Control-Allow-Origin': '*',
            }

        }).then((response) => {

            console.log(response);
        });
    }

    componentDidMount() {
        this.fetchData();
    }

出现错误

Failed to load http://swapi.co/api/people: Response for preflight is invalid (redirect)
:3000/#/:1 Uncaught (in promise) TypeError: Failed to fetch

我尝试了多种配置模式: cors、Access-Control-Allow-Origin: origin 、 other 。他们都不为我工作。

可能是什么问题?

最佳答案

为什么您遇到 HTTP 请求问题

服务器发送以下 header :

HTTP/1.1 301 Moved Permanently
Date: Thu, 30 Aug 2018 19:20:06 GMT
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: max-age=3600
Expires: Thu, 30 Aug 2018 20:20:06 GMT
Location: https://swapi.co/api/people/
Server: cloudflare
CF-RAY: 45299ce127d321b6-EWR

这些都不是 CORS header ,并且当请求重定向时,它需要 CORS。

如何修复

要解决此问题,您可以将 HTTP 更改为 HTTPS,这样可以避免重定向。

为什么自己添加 header 不起作用

由于 header 用于阻止网站发出请求,因此 header 必须由服务器发送。如果网站可以发送此信息,那么 CORS 保护就不会添加任何内容。

关于javascript - 努力从 fetch api 获取数据以获取对 http ://swapi. co 的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52103421/

相关文章:

ios - CloudKit fetchRecordWithID 错误 : "Fetching asset failed"

javascript - 从具有沙箱属性的 <iframe> 发出的 XHR 请求的原始 header 为 null

javascript - 使用 jquery 管理复选框并将这些值发送到 Controller 中

javascript - AngularJS 对跨源资源执行 OPTIONS HTTP 请求 => 错误 401

javascript - jQuery ajax CORS 请求

javascript - 当获取 url 正常时,为什么我会收到错误 400?

go - Axios 和 fetch 在 Golang 中给出空映射,即使在 url 编码时(添加了 header )

javascript - 为什么 Node fs.writeFile() 方法成功,但随后向浏览器发送了一个空文件?

javascript - 延迟按钮提交 Javascript