节点应用无法识别功能

时间:2016-04-24 06:35:27

标签: javascript node.js function

所以,我正在编写一个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.');
    }
  });
}`

但每次我发布帖子请求时都会收到错误

TypeError:twilio.send_sms_to不是函数

at /Users/jamesbradley/codeProjects/indulge/indulge_app/app.js:256:10

(这是" twilio.send_sms_to(new_user);"在app.js文件中)

...即使Nodemon运行服务器也没有问题。我做错了什么?

1 个答案:

答案 0 :(得分:1)

我的猜测是您忘记导出send_sms_to文件中的twilio.js功能。

尝试在其末尾添加module.exports.send_sms_to = send_sms_to;。否则,当您将模块导入其他地方时,他将不会成为模块的一部分。

如果我是对的,您可能想了解有关node.js模块here的更多信息。