首页 > 解决方案 > 努力从 fetch api 获取数据以获取对 http://swapi.co 的 get 请求

问题描述

我正在努力从我的 localhost creat-react-app 项目向http://swapi.co.in发出成功的请求。我已将我的 fetch api 请求放在我的 main contianer 的 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 Data 函数更新为

 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, others。他们都没有为我工作。

可能是什么问题?

标签: javascriptcorsfetch

解决方案


为什么您遇到 HTTP 请求问题

服务器发送以下标头:

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 标头,并且随着请求重定向,它需要 CORS。

怎么修

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

为什么自己添加标题不起作用

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


推荐阅读