Axios:基本身份验证不适用于 GET 请求 [英] Axios: Basic auth not working with GET request

查看:21
本文介绍了Axios:基本身份验证不适用于 GET 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使用基本身份验证的 axios get 请求,但我不断收到 401 状态代码.如果我正在执行发布请求,我的代码确实有效,所以我不知道我在这里做错了什么.

I have axios get request with basic auth, but i keep getting back a 401 status code. My code does work if i am doing a post request, so I don't know what i'm doing wrong here.

我的后端代码:

app.get('/api/find-user', (req, res) => {
    const username = req.body.username;
    axios.get('my-url', username, {
        auth:{
            username: 'my-username',
            password: 'my-password'
        }
    })
    .then(resp => {
        res.json({resp});
    })
    .catch(error => {
        res.send(error.response.status);
    })
});

我的前端代码:

findUser(user){
    const username = user;
    axios.get('/api/find-user', {username})
        .then(resp => {
            console.log(resp);
        })
        .catch(error => {
            console.log(error)
        })
}

同样,当我发帖创建新用户时,它确实有效,但是当我执行 GET 请求时,它一直说我未被授权.

Again when i am doing a post to create a new user it does work, but when i am doing a GET request it keeps saying i am not authorized.

如果您想投票反对,请成熟到足以解释原因.

If you feel like downvoting be adult enough to explain why.

推荐答案

你需要做的:

const usernamePasswordBuffer = Buffer.from(username + ':' + password);
const base64data = usernamePasswordBuffer.toString('base64');
const axiosObject = axios.create({
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Basic ${base64data}`,
    }
});

因为 Axios 需要使用用户名和密码对身份验证进行加密".

Because Axios needs the auth to be "encrypted" with both username and password.

这篇关于Axios:基本身份验证不适用于 GET 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆