You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Twilio Node.js实现短信OTP认证报错,请求调试帮助

Node.js使用Twilio发送OTP短信报错调试

我在Node.js中尝试用Twilio发送OTP短信做身份认证,但出现报错,报错位置在twilio.verify.services(process.env.TWILIO_SERVICE_SID)这一行。

我的代码:

require('dotenv').config()
const twilio = require("twilio")(process.env.TWILIO_ACCOUT_SID, process.env.TWILIO_AUTH_TOKEN)

const sendOTP = async(req, res)=>{
   const phoneNumber = req.body
       twilio.verify.services(process.env.TWILIO_SERVICE_SID)
       .verifications.create({
        to: `+${phoneNumber}`,
        channel: 'sms'
       }).then((data)=>{
        res.status(200).send({
            message: 'Verification is sent',
            phonenumber: phoneNumber,
            data
        })
       })
}

报错截图说明:

截图显示Twilio请求认证失败,提示权限不足或无效的认证凭据。

排查和解决方法:

  • 环境变量拼写错误:代码中TWILIO_ACCOUT_SID拼写错误,正确应为TWILIO_ACCOUNT_SID(少了字母N),这会导致Twilio无法验证身份,无法调用Verify服务。修正后重新加载环境变量。
  • 手机号获取错误:const phoneNumber = req.body直接获取整个请求体对象,拼接成+${phoneNumber}会生成无效号码格式+[object Object]。需改为获取请求体中的具体手机号字段,比如const phoneNumber = req.body.phoneNumber(根据前端传参字段名调整)。
  • Verify服务SID无效:确认process.env.TWILIO_SERVICE_SID是否正确,需在Twilio控制台创建Verify服务后,复制对应SID填入环境变量。
  • 添加错误捕获:当前代码未处理异步错误,添加catch块可捕获并返回具体错误信息,方便排查:
    twilio.verify.services(process.env.TWILIO_SERVICE_SID)
    .verifications.create({
      to: `+${phoneNumber}`,
      channel: 'sms'
    }).then((data)=>{
      res.status(200).send({
          message: 'Verification is sent',
          phonenumber: phoneNumber,
          data
      })
    }).catch((err) => {
      res.status(500).send({ 
          error: '发送失败', 
          reason: err.message,
          details: err
      })
    })
    

内容的提问来源于stack exchange,提问作者josef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 23:40:19