Node.js如何提取Authorization头凭证及Basic Auth报错解决方案
报错根因
TypeError: Cannot read property 'name' of undefined 是因为basicAuth(req)返回了undefined,说明后端没有正确获取到符合Basic认证格式的Authorization请求头。
解决步骤
- 第一步:确认
basic-auth依赖正确安装引入
先执行安装命令:npm install basic-auth
然后在User.js文件顶部引入依赖:const basicAuth = require('basic-auth') - 第二步:校验前端请求头发送是否正常
打开浏览器控制台「Network」标签,找到login请求,查看Request Headers中是否存在Authorization字段,值的格式必须为Basic 【Base64编码的账号密码串】,注意Basic和编码串之间必须有1个空格。 - 第三步:配置CORS允许Authorization头
跨域场景下浏览器默认会拦截自定义请求头,需要后端配置CORS规则放行Authorization头,如果你使用cors包,配置示例如下:const cors = require('cors'); app.use(cors({ allowedHeaders: ['Content-Type', 'Authorization'] })); - 第四步:可选手动解析Authorization头(无需第三方库)
如果你不想依赖basic-auth库,可以直接手动解析请求头,逻辑如下:router.post("/login", (req, res, next) => { const authHeader = req.headers.authorization; // 校验认证头是否存在且格式正确 if (!authHeader || !authHeader.startsWith('Basic ')) { return res.status(401).json({ message: '未提供有效认证信息' }); } // 解码获取账号密码 const base64Str = authHeader.slice(6); // 去掉前面的'Basic ' const decodeStr = Buffer.from(base64Str, 'base64').toString('utf-8'); const [mobileNumber, password] = decodeStr.split(':'); console.log("mobile number is ", mobileNumber); // 后续账号密码校验逻辑 });
内容的提问来源于stack exchange,提问作者suriyan
相关产品推荐
相关产品推荐

