嗨,我正在使用twilio API将消息发送到whatsapp数字,我需要从表单中获取数字和消息并将数据放入twilio API中,我现在不怎么构建逻辑,但是我这样做但是没有用,我得到了这个错误
(node:13568) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'body' of undefined
at sendMessage (/home/azoozalharte/سطح المكتب/s3ad7/controllers/index.js:12:21)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:13568) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:13568) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
POST /s3ad7 - - ms - -
所以这是我编写逻辑初始化的控制器文件
const S3aad7 = require('../models/s3ad7');
const accountSid = 'AC6e367ad8e26d8686c419f0f2e6e250e9';
const client = require('twilio')(accountSid ,process.env.AUTH_TOKEN);
module.exports = {
async sendMessage(req, res, next){
let msg = await S3aad7.create(req.body.msg);
client.messages
.create({
from: 'whatsapp:+18456179969',
body: msg.body,
to: `whatsapp:+${msg.receivedNumber}`
})
.then(message => console.log(message.sid));
}
}
这是我的视图文件,我需要从中获取数据
<form action="/s3ad7" method="POST">
<input type="text" name="msg[receivedNumber]" placeholder="الرقم مع رمز الدوله" id="">
<input type="text" name="msg[body]" placeholder="رسالتك" id="">
<input type="submit" name="" id="">
</form>
这是我的模型文件
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const s3ad7Schema = Schema({
receivedNumber: String,
body: String
});
module.exports = mongoose.model('S3ad7', s3ad7Schema);
这是twilio文档中的真实代码
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
// DANGER! This is insecure. See http://twil.io/secure
const accountSid = 'AC6e367ad8e26d8686c419f0f2e6e250e9';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.messages
.create({
from: 'whatsapp:+14155238886',
body: 'Hello there!',
to: 'whatsapp:+15005550006'
})
.then(message => console.log(message.sid));
我希望我解释了我到底需要什么
答案 0 :(得分:0)
尝试使用“ $ {msg.body}”而不是“ msg.body”,
module.exports = {
async sendMessage(req, res, next){
let msg = await S3aad7.create(req.body.msg);
client.messages
.create({
from: 'whatsapp:+18456179969',
body: ${msg.body},
to: `whatsapp:+${msg.receivedNumber}`
})
.then(message => console.log(message.sid));
}
}