如何在NodeJS中将数据变量传入Twilio短信内容
问题解决:将NodeJS变量传入Twilio短信内容
你的代码无法运行的核心问题是错误地给变量名加了美元符号$,NodeJS中直接使用变量名lowestPrice即可,不需要额外的$前缀。
正确实现代码
首先确保你已经提前定义并赋值了lowestPrice变量,然后按以下方式修改代码:
方式1:字符串拼接
const accountSid = 'abc123'; const authToken = 'def456'; // 先定义并赋值变量 const lowestPrice = 19.99; const client = require('twilio')(accountSid, authToken); client.messages .create({ body: 'Current Lowest Price: ' + lowestPrice, from: '+11234567890', to: '+10987654321' }) .then(message => console.log(message.sid));
方式2:ES6模板字符串(更简洁)
推荐使用模板字符串,可读性更强:
const accountSid = 'abc123'; const authToken = 'def456'; const lowestPrice = 19.99; const client = require('twilio')(accountSid, authToken); client.messages .create({ body: `Current Lowest Price: ${lowestPrice}`, from: '+11234567890', to: '+10987654321' }) .then(message => console.log(message.sid));
注意事项
- 必须保证
lowestPrice变量在Twilio API调用前已被正确定义并赋值,否则会抛出ReferenceError - 如果
lowestPrice是复杂类型(比如对象),记得先转换成字符串(比如用JSON.stringify()),避免短信内容显示为[object Object]
内容的提问来源于stack exchange,提问作者Redink
相关产品推荐
相关产品推荐

