ReactJS集成MSG91验证OTP时提示无效密钥的问题排查
解决MSG91 OTP验证时的「Invalid Auth key」错误
问题根源分析
你的代码存在几个关键问题导致Auth key验证失败:
- 请求方法不匹配:MSG91的OTP验证接口要求使用
POST请求,你当前用了GET,且试图从req.body获取参数(GET请求无请求体),导致参数传递异常。 - Proxy参数拼接逻辑错误:
setupProxy.js中pathRewrite尝试从请求体拿mobile和otp,但GET请求没有body,这两个参数会为空,同时拼接方式会导致最终请求的参数格式混乱。 - Content-Type设置错误:GET请求不需要设置
Content-Type: application/json,反而会让接口解析逻辑异常。
修复方案及代码调整
1. 修改App.js中的verifyOTP函数
将请求改为POST,把参数放在请求体中,而非URL query:
<button onClick={verifyOTP}>Verify OTP</button> const verifyOTP = async () => { const mobileNumber = mobile; try { const response = await fetch('/api/verifyOTP', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ mobile: `91${mobileNumber}`, otp: otp }) }); if (response.ok) { const responseData = await response.json(); if (responseData.type === 'success' && responseData.message === 'OTP verified successfully') { console.log('OTP Verified Successfully'); } else { console.error('Failed to verify OTP:', responseData.message); } } else { console.error('Error verifying OTP. Status code:', response.status); } } catch (error) { console.error('Error verifying OTP:', error); } };
2. 调整setupProxy.js配置
改为支持POST请求,正确传递Auth key和请求参数:
const { createProxyMiddleware } = require('http-proxy-middleware'); const authKey = 'xxxxxxxxxxxxxxxxxx'; module.exports = function(app) { app.use( '/api/verifyOTP', createProxyMiddleware({ target: 'https://control.msg91.com/api/v5/otp/verify', changeOrigin: true, methodFilter: ['POST'], pathRewrite: { '^/api/verifyOTP': '' }, onProxyReq: (proxyReq, req, res) => { // 将Auth key添加到请求的query参数中 const url = new URL(proxyReq.path, proxyReq.protocol + '//' + proxyReq.host); url.searchParams.append('authkey', authKey); proxyReq.path = url.pathname + url.search; // 处理POST请求体,确保参数正确传递 if (req.body) { const bodyData = JSON.stringify(req.body); proxyReq.setHeader('Content-Type', 'application/json'); proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData)); proxyReq.write(bodyData); proxyReq.end(); } } }) ); }
额外验证点
- 确认你的Auth key是MSG91控制台中OTP服务对应的有效密钥,而非其他服务的密钥。
- 检查手机号格式是否正确(必须带国家码91,且无多余符号)。
- 确保OTP是最近发送的未过期验证码。
内容的提问来源于stack exchange,提问作者puja singh
相关产品推荐
相关产品推荐

