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

Express.js调用fast2sms提示发送成功但手机未收短信问题排查

Express+fast2sms短信发送故障排查

问题概述

  • 基于Express.js开发作业项目,功能逻辑为从请求对象提取参数,调用fast2sms API向指定手机号发送短信
  • 核心逻辑编写完成后测试,目标手机号始终无法收到短信,排查4小时未定位问题
  • 接口执行无报错,但message sent successfully提示仅输出在终端,未作为接口响应返回
  • 已在app.js中添加console.log(req.body)打印请求体用于排查

问题代码

const fast2sms = require('fast-two-sms');
app.post("/sendmessage", async(req,res)=>{
    try {
        const {client_email, client_name, income_per_month, savings_per_month, mobile_number} = req.body;
        var options = {
            authorization : process.env.API_KEY,
            message : 'hello',
            numbers : [mobile_number]
        } 
        const response = await fast2sms.sendMessage(options);
        res.send(response.message);
    } 
    catch (error) {
        res.send("Failed to send SMS to the client")
    }
})

排查修复步骤

  • 先解决响应异常问题
    终端打印的message sent successfully不是接口返回内容,是fast-two-sms库内部默认的日志输出。如果接口没有正常返回响应,首先检查是否缺少Express内置的请求体解析中间件:
    必须在所有路由定义前加载以下中间件,否则*req.body为undefined*,提取到的手机号为空,直接导致短信发送失败:
    // 路由定义前添加
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));
    
  • 逐一排查收不到短信的核心原因
    • 确认环境变量加载正常:如果使用dotenv管理环境变量,必须在入口文件最顶部执行*require('dotenv').config(),否则process.env.API_KEY为undefined*,API鉴权失败不会下发短信
    • 校验手机号格式:fast2sms默认仅支持印度地区手机号,要求传入10位纯数字、不带+91国家码,非印度号码或格式不符合要求的号码会被API直接拦截
    • 检查fast2sms账户状态:登录fast2sms后台确认账户有剩余短信额度,当前使用的API Key未过期、未开启IP白名单限制
    • 禁用库内部日志避免干扰:调用sendMessage时在options中添加logger: false参数,关闭库自带的console打印,避免和接口响应混淆,修改后的配置如下:
    const options = {
        authorization: process.env.API_KEY,
        message: 'hello',
        numbers: [mobile_number],
        logger: false
    }
    
  • 优化错误捕获逻辑
    当前catch块仅返回固定失败提示,没有打印错误详情,无法定位API调用失败的具体原因,修改为以下写法即可拿到完整错误信息:
    catch (error) {
        console.log('短信发送错误详情:', error.response?.data || error.message);
        res.status(500).send("Failed to send SMS to the client")
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 20:24:28