Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Reactjs中获取身份验证API_Reactjs_Api_Ecmascript 6_Fetch - Fatal编程技术网

在Reactjs中获取身份验证API

在Reactjs中获取身份验证API,reactjs,api,ecmascript-6,fetch,Reactjs,Api,Ecmascript 6,Fetch,我正在开发React web应用程序,需要从具有用户名和密码的API获取数据。我一直在尝试我搜索的关于这个问题的几个代码,但它们不起作用,我不断得到401错误。我真的卡住了。这是我的代码: class Global extends Component{ constructor(props){ super(props); this.state = { query: '' } } search(){ l

我正在开发React web应用程序,需要从具有用户名和密码的API获取数据。我一直在尝试我搜索的关于这个问题的几个代码,但它们不起作用,我不断得到401错误。我真的卡住了。这是我的代码:

class Global extends Component{
    constructor(props){
        super(props);
        this.state = {
            query: ''
        }
    }

search(){
    let url = 'my URl';

    let headers = new Headers();

    headers.append('Authorization', 'Basic ' + 'base64 encoaded username and password');

    fetch(myurl, { method:'GET',
       headers: headers,
    })
    .then(response => response.json())
    .then(json => console.log(json));
    //.done fetching;
}
试试这个

var url = "https://yourUrl";
var bearer = 'Bearer '+ bearer_token;
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
    'Authorization': bearer,
    'X-FP-API-KEY': 'iphone',
    'Content-Type': 'application/json'}
}).then((responseJson) => {
    var items = JSON.parse(responseJson._bodyInit);
})
.catch(error => this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));

谢谢,但是您的代码是关于从承载令牌api获取数据的,但是我的api是基本的。这个答案并没有解决这个问题。您的代码看起来是正确的。这很可能是因为用户名和密码的base64编码错误。请记住,您必须对username:password进行base64编码。示例:btoa(“管理员:机密”)