javascript - Node : undefined is not a new function 'new'

标签 javascript node.js twilio

我正在尝试 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 所在的位置,而不是您当前接收的客户端对象(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 docs显示了以这种方式使用模块的示例(将导出与实际的 Rest 客户端分开)。

关于javascript - Node : undefined is not a new function 'new' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36671915/

相关文章:

javascript - Chrome 以百分比正确显示自适应图像和宽度,Firefox 不正确

javascript - 用javascript替换正则表达式中的部分文本

javascript - 如何基于json数据显示多个动态highcharts

sms - 火箭聊天 : How to send SMS Messages to Livechat channel from mobile

ruby-on-rails - 如何使用 Rails 配置 Twilio 短信网关?

javascript - 如何在用户的查看范围内有效地在 Google map 上显示项目?

node.js - Express - 从 Web 服务返回二进制数据

node.js - 将参数附加到 URL

javascript 给出意想不到的结果

Twilio Studio - 如何挂断电话?