JS构造函数无法看到变量

时间:2018-05-13 22:22:04

标签: javascript node.js typescript firebase twilio

我正在尝试使用TypeScript在Firebase函数上使用Twilio Access Token。

export const returnToken = functions.https.onRequest((req, res) => {
  const twilioAccessToken = twilio.jwt.AccessToken;
  const envconf = functions.config();
  const twilioAccountSid = envconf.twilio.sid; //saved them on environment
  console.log(twilioAccountSid); //prints out fine
  console.log(typeof twilioAccountSid !== "undefined"); //returns true
  const twilioApiKey = envconf.twilio.apikey;
  console.log(twilioApiKey); //prints fine too
  const twilioApiSecret = envconf.twilio.apisecret;
  console.log("gonna make a token"); //prints 

  const token = twilioAccessToken( //here it says TypeError: Cannot set property 'accountSid' of undefined
    twilioAccountSid,
    twilioApiKey,
    twilioApiSecret
  )
  console.log("gonna make a grant");
  const grant = new twilioAccessToken.VideoGrant();
  token.addGrant(grant);
  grant.room = "someroom";
  token.identity = "someid";
  res.send(token.toJwt());
})

我得到了twilioAccessToken构造函数的错误   TypeError: Cannot set property 'accountSid' of undefined

1 个答案:

答案 0 :(得分:2)

查看来源 - >

function AccessToken(accountSid, keySid, secret, options) {
  if (!accountSid) { throw new Error('accountSid is required'); }
  if (!keySid) { throw new Error('keySid is required'); }
  if (!secret) { throw new Error('secret is required'); }
  options = options || {};
  this.accountSid = accountSid;

AccessToken是一个构造函数,但是你将它称为常规函数..

const token = twilioAccessToken( 

您需要使用new

const token = new twilioAccessToken( 

普通的Javascript表示法是一个函数以大写字母开头,它暗示它是一个构造函数。为了符合此标准,我想您还要将twilioAccessToken重命名为TwilioAccessToken ..