所以,我正在编写一个 Node 应用程序,并且尝试添加一个在创建新用户时调用的函数。我使用 Twilio API 是为了在用户注册该应用后向某人发送短信。
app.js
var express = require('express');
var db = require('./models');
var bodyParser = require('body-parser');
var methodOverride = require("method-override");
var app = express();
var session = require('express-session');
var app = express();
var twilio = require('./js/twilio.js');
// app.set('port', (process.env.PORT || 3000));
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.post("/signup", function (req, res) {
// Creating object to pass into db and twilio:
var new_user = {
first_name : req.body.first_name,
last_name : req.body.last_name,
phone : req.body.phone,
partner_phone : req.body.partner_phone,
email : req.body.email,
password : req.body.password
};
console.log("The new_user is: ", new_user)
twilio.send_sms_to(new_user);
db.User.create({first_name: new_user.first_name, last_name: new_user.last_name, phone: new_user.phone, partner_phone: new_user.partner_phone, email: new_user.email, password: new_user.password}).then(function(user){
res.render("login");
});
});
twilio.js
var send_sms_to = function (user) {
var client = new twilio.RestClient('secret key', 'super secret key'), msg = "Hello potential new user!",
phone = user.partner_phone,
name = user.first_name + " " + user.last_name;
console.log("Entries are: ", user.phone, user.first_name)
client.sms.messages.create({
to: phone,
from:'+16507970229',
body: msg
}, function(error, message) {
// The HTTP request to Twilio will run asynchronously. This callback
// function will be called when a response is received from Twilio
// The "error" variable will contain error information, if any.
// If the request was successful, this value will be "falsy"
if (!error) {
// The second argument to the callback will contain the information
// sent back by Twilio for the request. In this case, it is the
// information about the text messsage you just sent:
console.log('Success! The SID for this SMS message is:');
console.log(message.sid);
console.log('Message sent on:');
console.log(message.dateCreated);
} else {
console.log('Oops! There was an error.');
}
});
}`
但是每次我运行 post 请求时都会收到错误
类型错误:twilio.send_sms_to 不是函数
位于/Users/jamesbradley/codeProjects/indulge/indulge_app/app.js:256:10
(这是 app.js 文件中的“twilio.send_sms_to(new_user);”行)
...即使 Nodemon 运行服务器没有任何问题。我做错了什么?
最佳答案
我的猜测是您只是忘记导出 twilio.js
文件中的 send_sms_to
函数。
尝试在其末尾添加module.exports.send_sms_to = send_sms_to;
。否则,当您将其导入其他地方时,他将不会成为该模块的一部分。
如果我是对的,您可能想了解有关 Node.js 模块的更多信息 here .
关于javascript - Node 应用程序无法识别功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36820053/