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

使用Node.js实现Twilio短信收发遇502错误求助

Fixing Twilio Auto-Reply 502 Bad Gateway Error

Hey there, let's get your Twilio auto-reply working properly—those 502 errors are usually easy to squash once you spot the missing pieces. Here's what's going wrong and how to fix it:

Key Issues in Your Code

  • Missing Request Body Parsing: Twilio sends webhook data as application/x-www-form-urlencoded, but your Express app isn't set up to parse this format. Without parsing, the server can't process Twilio's request, leading to the 502 error.
  • Typo in Account SID: You have a typo accounSid (missing a "t")—this will break your Twilio client initialization, though it might not be the immediate cause of the 502.

Corrected Code

Here's your code with fixes applied:

// Fix the typo: accounSid → accountSid
const accountSid = 'xxxxxxxxxxxxx';
const authToken = 'xxxxxxxxxxxxx';
const client = require('twilio')(accountSid, authToken);

// Optional: Send initial test message (added error handling for debugging)
client.messages.create({
  to: '+13101234567',
  from: '+13109876543',
  body: 'test'
})
.then((message) => { console.log(message.sid) })
.catch(err => console.error('Error sending test message:', err));

const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const app = express();

// Add this middleware to parse URL-encoded request bodies (required for Twilio webhooks)
app.use(express.urlencoded({ extended: false }));

app.post('/sms', (req, res) => {
  console.log('Received SMS from:', req.body.From); // Log incoming request to debug
  const twiml = new MessagingResponse();
  twiml.message('testing 123');
  
  // Simplify response handling (Express handles headers more reliably this way)
  res.type('text/xml').send(twiml.toString());
});

http.createServer(app).listen(1337, () => {
  console.log('express server listening on port 1337');
});

Additional Checks to Ensure It Works

  • Restart Your Server: After making these changes, stop and restart your local server to apply the new middleware.
  • Verify Ngrok Setup: Make sure your ngrok URL is active (check the ngrok terminal for the current HTTPS URL), and that you've added /sms to the end in Twilio's console (e.g., https://abc123.ngrok.io/sms).
  • Twilio Webhook Method: Confirm Twilio is set to send a POST request to your webhook (not GET).
  • Check Logs: Keep an eye on your server terminal—you should see a log entry when Twilio sends a request to /sms if everything is connected properly.

Once you've made these fixes, send a reply to your initial test SMS, and you should get the "testing 123" response right away!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:48:20