React.js集成Twilio发送OTP SMS遇404错误求助
接口404错误排查与修复
问题现象
调用sendOTP和verifyOTP接口时出现404错误:
RegistrationForm.js:21 POST http://localhost:3000/api/sendOTP 404 (Not Found) RegistrationForm.js:21 POST http://localhost:3000/api/verifyOTP 404 (Not Found)
核心错误点及修复方案
1. Express路由路径格式错误
后端server.js中路由路径使用了相对路径前缀./,不符合Express路由规则,Express要求路由路径必须以/开头。
错误代码(server.js):
app.post('./api/sendOTP', async (req, res) => { ... }) app.post('./api/verifyOTP', async (req, res) => { ... })
修复后代码:
app.post('/api/sendOTP', async (req, res) => { ... }) app.post('/api/verifyOTP', async (req, res) => { ... })
2. 前端请求路径不一致
前端RegistrationForm.js中handleVerifyClick函数使用了相对路径./api/verifyOTP,而handleSendOTP使用了绝对路径/api/sendOTP,路径解析逻辑混乱导致请求地址错误。
错误代码(RegistrationForm.js):
const response = await fetch('./api/verifyOTP', { ... })
修复后代码:
const response = await fetch('/api/verifyOTP', { ... })
3. 前后端端口冲突(关键隐藏问题)
React开发服务器默认占用3000端口,后端Express也监听3000端口,会导致端口冲突,后端服务无法正常提供接口能力(前端请求会被自身开发服务器拦截)。
修复方案:
- 修改后端
server.js的监听端口为3001:app.listen(3001, () => { console.log('Server is running on port 3001'); }); - 前端配置代理:在React项目的
package.json中添加代理配置,这样前端仍可使用/api/xxx的路径发起请求,会自动转发到3001端口的后端:"proxy": "http://localhost:3001"
验证步骤
- 重启后端服务器,确认控制台日志显示
Server is running on port 3001 - 重启前端开发服务器
- 再次测试发送和验证OTP功能,确认404错误消失
内容的提问来源于stack exchange,提问作者Techno Hub
相关产品推荐
相关产品推荐

