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

集成Twilio API的ReactJS应用部署Vercel报错(本地运行正常)

React+Express+Twilio项目Vercel部署后短信发送失败的解决方案

核心问题分析

从代码和部署场景来看,导致失败的主要原因有以下几点:

  • 前端硬编码调用localhost:4000,部署到Vercel后无法访问本地后端服务
  • 后端环境变量使用了React专属的REACT_APP_前缀,Node.js后端无法读取
  • 后端未适配Vercel的API路由规则
  • 未确保手机号符合Twilio要求的E.164格式

分步修复方案

1. 修正前端API调用地址

前端handleSendSMS中的http://localhost:4000/send-text是本地测试地址,部署后需替换为后端实际部署地址。若将后端作为Vercel API函数部署,直接使用相对路径:

const handleSendSMS = async () => {
  try {
    // 使用Vercel API路由的相对路径
    const response = await axios.get('/api/send-text', {
      params: {
        recipient: phoneNumber
      },
    });

    console.log('SMS Sent:', response.data);
  } catch (error) {
    console.error('Error sending SMS:', error.response?.data || error.message);
  }
};

2. 调整后端为Vercel兼容的API函数

Vercel要求Node.js后端接口放在/api目录下,创建api/send-text.js文件替代原server/index.js:

const twilio = require('twilio');

// 移除REACT_APP_前缀,直接使用环境变量
const accSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = new twilio(accSid, authToken);

export default function handler(req, res) {
  if (req.method !== 'GET') {
    return res.status(405).send('Method Not Allowed');
  }

  const { recipient } = req.query;

  // 验证手机号是否符合E.164格式(如+8613xxxxxxxxx)
  if (!recipient || !/^\+[1-9]\d{1,14}$/.test(recipient)) {
    return res.status(400).send('Invalid phone number format (must be E.164)');
  }

  client.messages.create({
    body: `感谢您到访派出所。请在访问后点击链接填写反馈表单:https://feedback-system-police-private.vercel.app/myVisits,填写反馈是必填项。\n此致`,
    to: recipient,
    from: '+19287560963' // 替换为你的Twilio号码
  })
  .then(() => {
    res.status(200).send('短信发送成功');
  })
  .catch((error) => {
    console.error('发送短信出错:', error);
    res.status(500).send(`发送短信失败:${error.message}`);
  });
}

3. 配置Vercel环境变量

在Vercel项目的Settings > Environment Variables中添加以下变量:

  • TWILIO_ACCOUNT_SID: 你的Twilio账户SID
  • TWILIO_AUTH_TOKEN: 你的Twilio认证令牌

4. 修复手机号格式问题

Twilio要求接收号码必须是E.164格式(带国家码),在前端添加格式处理:

const handleChange = (e) => {
  const { name, value } = e.target;
  if (name === 'mobile') {
    // 自动添加中国国家码,去除空格
    const formattedNumber = value.startsWith('+') ? value : `+86${value.replace(/\s/g, '')}`;
    setPhoneNumber(formattedNumber);
  }
  setForm({ ...form, [name]: value });
};

5. 移除不必要的CORS配置

使用Vercel API路由时,无需额外配置CORS,平台会自动处理跨域请求。

额外注意事项

  • 确保Twilio账户已验证接收号码(免费账户仅支持发送到验证过的号码)
  • 检查Twilio账户余额是否充足
  • 部署后可通过Vercel的Functions日志查看后端错误详情

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 01:56:12