如何通过在React中传递axios中的基本身份验证来进行api调用

时间:2020-03-23 04:58:16

标签: api axios

我有一个用于登录的api,它的工作原理如下。要进行api调用,我必须像这样添加授权basic auth

Adding auth

身体

passing body

但是问题是当我通过axios发出api请求时,它总是给我这样的响应错误

Error: "Request failed with status code 401"
    createError createError.js:17
    settle settle.js:19
    handleLoad xhr.js:60

我提出了类似要求。

//TODO: AUTH Actions
export const login = (username, password) => (dispatch) => {
    //User Loading:
    dispatch({ type: USER_LOADING });
    //Make API Call here

    console.log('featch adata', data);
    axios.post('https://api.smartocart.com/oauth/token', {
        data: {
            username: username,
            password: password,
            grant_type: 'password',
        },
        auth: {
            username: 'topseller',
            password: 'topseller'
        }
    })
        .then((res) => {
            console.log('Then response', res)
        }).catch(err => {
            console.log(err)
        })
    // console.log('Action login', username, password);

}

1 个答案:

答案 0 :(得分:0)

如前所述,尝试将config对象作为.post函数的第三个参数,Request post主体应为第二个参数。 https://github.com/axios/axios#axiosposturl-data-config-1

您正在尝试类似axios.post(url, config)之类的方法,但是没有该功能。您应该使用axios.post(url, data, config)

axios.post('https://api.smartocart.com/oauth/token', 
         {
            username: username,
            password: password,
            grant_type: 'password',
         }, 
         {
           auth: {
             username: 'topseller',
             password: 'topseller'
           }
         }
        ).then((res) => {
            console.log('Then response', res)
        }).catch(err => {
            console.log(err)
        })
相关问题