Axios集成API弹出用户名密码弹窗 如何免弹窗完成登录
你碰到的弹窗是浏览器默认的HTTP Basic Auth认证窗口,截图如下:
只要请求时主动带上符合要求的认证信息,浏览器就不会再弹出验证窗口。你用的Axios已经内置了Basic Auth的配置支持,不用自己手动编码处理,按以下方式配置即可:
方法1:单个请求单独配置认证信息
直接在Axios.get的第二个参数(请求配置对象)中加入auth字段,填入你的账号密码即可,修改后的业务代码如下:
const getPlate = () => { let licensePlate = document.getElementById('licensePlate'); let licensePlateNumber = licensePlate.value; if (licensePlate.value === "") { alert('¡Debe introducir el número de matrícula para poder avanzar!'); } else { Axios.get('替换为你的实际接口地址', { // 新增认证配置 auth: { username: '你的实际用户名', password: '你的实际密码' } }).then((response) => { let plate = response; // 注意原代码的i变量未定义,可根据实际业务调整取值下标 console.log(plate.data[0].make); }); } }
页面部分代码无需调整:
<div id="carDataContainer"> <div id="licensePlateContainer"> <input type="text" name="licensePlate" id="licensePlate" placeholder="Matrícula - ej. 001 BNDO"></input> <button type="button" id="plateBtn" onClick={ getPlate }>Search</button> </div> </div>
方法2:全局配置Axios默认认证信息
如果你有多个请求都需要使用同一套账号密码访问同域名接口,可以直接配置Axios全局默认参数,所有请求都会自动带上认证信息,无需每个请求重复编写:
// 这段代码放在所有Axios请求执行之前即可 Axios.defaults.auth = { username: '你的实际用户名', password: '你的实际密码' }
注意事项
如果代码运行在前端浏览器环境,账号密码直接写在前端代码中会完全暴露给所有访问用户,存在极高的泄露风险。如果是生产环境使用,建议新增后端代理层:前端请求你自己的后端服务,由后端服务带上认证信息请求目标API,避免账号密码泄露。
内容的提问来源于stack exchange,提问作者Michael Haydn
相关产品推荐
相关产品推荐

