【问题标题】:React Fetch api fails [duplicate]React Fetch api失败[重复]
【发布时间】:2019-12-18 12:22:50
【问题描述】:

我正在尝试从 randomuser.me 中获取,我的组件是:

import React, { Component } from 'react';

class RandomUser extends Component {
    state = {
        contacts:[]
    }

    async   componentDidMount(){
        const url = 'http://api.randomuser.me?results=20';
        const response = await fetch(url, {mode: 'cors'});
        const data = await response.json();
        console.log(data);
    }

    render(){
    console.log(this.state.contacts);
        return (
            <div>
                <h2>Users:</h2>
            </div>
            )
    }
}

export default RandomUser;

我在控制台看到的错误是:

Access to fetch at 'http://api.randomuser.me/?results=20' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我该如何纠正?我没有使用任何本地服务器,而是依赖 randomuser.me

请帮忙。

【问题讨论】:

    标签: javascript reactjs cors fetch-api


    【解决方案1】:

    在不设置获取模式的情况下尝试它。我也有一个使用 randomuser API 的 React 项目,我只是 await fetch(url) 并且一直有效。

    【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多