Axios配置Authorization时报Unauthorized未授权错误如何解决?
问题诊断
你的配置存在3个核心错误:
- 位置错误:
Authorization是请求头字段,必须放在headers配置项内部,你当前写在配置根层级,Axios不会识别为请求头发送 - 格式错误:Basic Auth的
Authorization头要求固定格式为Basic <base64编码的用户名:密码字符串>,不能直接传递包含Username、Password的对象 - 凭证错误:你当前使用的账号密码不符合官方测试要求,官方要求的凭证为用户名
test、密码test
修复方案
方案1:使用Axios内置auth配置项(最简方案,无需手动编码)
Axios提供了专门的auth配置字段,会自动完成Basic Auth的编码和头信息拼接,代码如下:
const res = axios.get("http://aaaaaaaaa.com", { auth: { username: 'test', password: 'test' }, headers: { 'Content-Type': 'application/json' } });
方案2:手动构造Authorization头
如果需要自己控制编码逻辑,也可以手动生成头信息:
// 浏览器环境下拼接用户名密码后转base64编码 const basicAuth = 'Basic ' + btoa('test:test'); const res = axios.get("http://aaaaaaaaa.com", { headers: { 'Content-Type': 'application/json', 'Authorization': basicAuth } });
注意:如果是Node.js环境没有浏览器内置的
btoa方法,可以用Buffer.from('test:test').toString('base64')实现同等编码效果。
内容的提问来源于stack exchange,提问作者user6236933
相关产品推荐
相关产品推荐

