React Fetch API失败

时间:2019-08-11 18:12:34

标签: javascript reactjs cors fetch-api

我正在尝试从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;

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

enter image description here

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

请帮助。

1 个答案:

答案 0 :(得分:-1)

尝试此操作,而不在获取中设置模式。我也有一个使用randomuser API的React项目,我只是Union,而且一直有效。