如何解决当我尝试在 nodejs 中使用 twilio 从我的前端发送短信时出现这些错误
我正在尝试通过自定义 API URL 从我的前端发送 OTP,该 URL 使用 nodejs 后端服务器来触发请求。但是我'。收到以下错误。
后端代码:
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require("twilio")(accountSid,authToken);
router.post("/notification",(req,res) => {
const type = req.query.type || "sms";
const ph = `+${req.query.ph}` || "";
const email = req.query.email || "";
const reason = req.query.reason || "notification";
const msg = req.body.text || "";
if (type === "sms" && reason === "auth") {
const OTP = getRandom(1000,2000);
console.log(`OTP is - ${OTP}`);
client.messages
.create({
body: `Hi,Im Sandip. OTP is - ${OTP}`,from: "+12012994953",to: ph,})
.then((message) => res.send({ ...message,otp: OTP }))
.catch((err) => console.log(err,"err"));
}else{ ...some other logic }
在这个 URL 上我请求这些参数
http://localhost:4000/api/auth/notification?type=sms&reason=auth&ph=918697836806
我在控制台中遇到的错误
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Twilio'
| property '_accounts' -> object with constructor 'Accounts'
--- property 'twilio' closes the circle
at JSON.stringify (<anonymous>)
at stringify (D:\Edureka\Projects\Full Stack Projects\E-commerce\backend\node_modules\express\lib\response.js:1123:12)
at ServerResponse.json (D:\Edureka\Projects\Full Stack Projects\E-commerce\backend\node_modules\express\lib\response.js:260:14)
at ServerResponse.send (D:\Edureka\Projects\Full Stack Projects\E-commerce\backend\node_modules\express\lib\response.js:158:21)
at D:\Edureka\Projects\Full Stack Projects\E-commerce\backend\controller\authController.js:122:30
at Promise_then_fulfilled (D:\Edureka\Projects\Full Stack Projects\E-commerce\backend\node_modules\q\q.js:766:44)
at Promise_done_fulfilled (D:\Edureka\Projects\Full Stack Projects\E-commerce\backend\node_modules\q\q.js:835:31)
at Fulfilled_dispatch [as dispatch] (D:\Edureka\Projects\Full Stack Projects\E-commerce\backend\node_modules\q\q.js:1229:9)
at Pending_become_eachMessage_task (D:\Edureka\Projects\Full Stack Projects\E-commerce\backend\node_modules\q\q.js:1369:30)
at RawTask.call (D:\Edureka\Projects\Full Stack Projects\E-commerce\backend\node_modules\asap\asap.js:40:19)
at flush (D:\Edureka\Projects\Full Stack Projects\E-commerce\backend\node_modules\asap\raw.js:50:29)
提前致谢
解决方法
res.send()
尝试对您提供的对象进行字符串化。根据{{3}},你想要
.then((message) => res.send({ message: message.sid,otp: OTP }))
而不是对从其 API 返回的整个 message
对象进行解构。
编辑:试试这个。我认为它可以满足您的需求。您应该能够从 console.log 中得知您要发回的内容。
.then((twilioResponse) => {
message = twilioResponse.sid
message.otp = OTP
console.log(message)
res.send(message)
} )
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。