当 url 在 React Native 中受密码保护时,如何做 axios.get?

How to do axios.get when the url is password protected in react native?

我正在尝试 axios.get。当我在浏览器上输入 url 并点击进入浏览器时,询问我用户名和密码。但是我不知道如何在get方法中的axios header中设置密码和用户名。 Swagger UI 是 http://api.myslambook.in/swagger/#

这是我的代码:

import axios from 'axios';
import base64 from 'react-native-base64'

export function FriendRequests ( ) {

    state = {
        serverData: [],
    };

    const tok = 'myusername:mypassword';
    const hash = base64.encode(tok);
    const Basic = 'Basic ' + hash;

    axios.get('http://api.myslambook.in/users', {headers : { 'Authorization' : Basic }})
    .then(res => {
        const serverData = res.data;
        this.setState({ serverData });
    })
    .catch(err => console.log(err));
}

我在控制台中收到此错误:

Request failed with status code 401. 

谁能帮帮我?提前致谢。

对于基本身份验证,可以使用 auth 对象:

axios.get('http://api.myslambook.in/users', {
    auth: {
        username: 'janedoe',
        password: 's00pers3cret'
    }
}).then(res => {
    const serverData = res.data;
    this.setState({serverData});
}).catch(err => console.log(err));

修复 Can't find variable: btoa 错误:

npm i -S base-64

并将以下内容添加到 index.js

import {decode, encode} from 'base-64'

if (!global.btoa) {
    global.btoa = encode;
}

if (!global.atob) {
    global.atob = decode;
}

查看文档:https://github.com/axios/axios#request-config