NodeJS:undefined不是一个新的函数'new'

我正在尝试Node JS Twilio指南的代码片段: https ://www.twilio.com/blog/2013/03/introducing-the-twilio-module-for-node-js.html

var twilio = require('twilio')('AUTH-ID','AUTH-SECRET'); http = require('http'); http.createServer(function (req, res) { var resp = new twilio.TwimlResponse(); resp.say({voice:'woman'}, 'ahoy hoy! Testing Twilio and node.js'); res.writeHead(200, { 'Content-Type':'text/xml' }); res.end(resp.toString()); }).listen(1337); console.log('Visit http://localhost:1337/ in your browser to see your TwiML document!'); 

当我启动这个片段并访问URL时,我得到了这个回应:

 /Users/unicornherder/Desktop/Porter/inbound.js:7 var resp = new twilio.TwimlResponse(); ^ TypeError: undefined is not a function at Server.<anonymous> (/Users/unicornherder/Desktop/Porter/inbound.js:7:16) at Server.EventEmitter.emit (events.js:98:17) at HTTPParser.parser.onIncoming (http.js:2108:12) at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23) at Socket.socket.ondata (http.js:1966:22) at TCP.onread (net.js:527:27) 

有人能解释我在做什么错吗?

您需要保存导出的require('twilio') ,因为这是TwimlResponse所在的TwimlResponse ,而不是您当前正在接收的客户端对象( require('twilio')(..)require('twilio').RestClient(..) )。 所以做这个,而不是:

 var http = require('http'); var twilio = require('twilio'); // or `var twilioClient = twilio(...)` var twilioClient = new twilio.RestClient('AUTH-ID','AUTH-SECRET'); http.createServer(function (req, res) { var resp = new twilio.TwimlResponse(); resp.say({voice:'woman'}, 'ahoy hoy! Testing Twilio and node.js'); res.writeHead(200, { 'Content-Type':'text/xml' }); res.end(resp.toString()); }).listen(1337); 

FWIW twilio文档显示了以这种方式使用模块的示例(将出口与实际的Rest客户端分开)。

从导入中删除参数“AUTH-ID”和“AUTH-SECRET”。

如果在导入过程中传递这些参数,则正在初始化其余客户端,而twiliovariables不会代表模块对象。 因此,TwimlResponse对象将是未定义的。

我正在看这个博客,看来如果你正在创build一个响应,这是你应该在你的代码中要求的:

 var twilio = require('twilio');