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

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

问题描述

我有axios通过基本身份验证获取请求,但是我一直在找回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需要使用用户名和密码对auth进行加密".

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

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

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