从Node.JS回调函数启用CORS

时间:2017-08-10 19:23:08

标签: javascript node.js ajax twilio twilio-api

我正在尝试使用Twilio函数来处理Twilio应用程序的令牌生成。我以前使用Node.js + Express Server来完成此任务,但我不知道如何在这种类型的环境中找出启用CORS。
我的客户端代码如下所示:

$('#new-twilio').click(function(){
        var toNum = this.value;
        if(token == undefined) {
            $.getJSON('https://my-twilio-function/endpoint').done(function(data){
                token = data.token;
                Twilio.Device.setup(token, {debug: true});
                Twilio.Device.ready(function(device){
                    Twilio.Device.connect({"PhoneNumber": toNum});  
                });
            }).fail(function(error){
                alert("Failure!");
                alert(JSON.stringify(error));
            });
        } else {
            Twilio.Device.connect({"PhoneNumber": toNum});
        }
    });


我的功能代码如下:

exports.handler = function(context, event, callback) {
    const client = context.getTwilioClient();
    const ClientCapability = require('twilio').jwt.ClientCapability;
    const responseHeaders = {  
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET, POST",
        "Access-Control-Allow-Headers": "content-type, accept",
        "Content-Type": "application/json"
    };
    let identity = "sampleIdentity";
    const capability = new ClientCapability({
      accountSid: context.ACCOUNT_SID,
      authToken: context.AUTH_TOKEN
    });
    capability.addScope(new ClientCapability.IncomingClientScope(identity));
    capability.addScope(new ClientCapability.OutgoingClientScope({
      applicationSid: context.TWILIO_TWIML_APP_SID
    }));
    console.log(capability.toJwt());
    callback(null, {headers: responseHeaders, identity: identity, token: capability.toJwt()});

};
值得注意的是,console.log证明这个函数正在返回我需要的确切令牌,但我继续得到这个错误:

XMLHttpRequest cannot load https://my-twilio-function/endpoint. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.


显然,我的twilio功能是一个真正的URL。就像我谷歌一样,我找不到如何允许对这种类型的节点方法进行访问控制。

3 个答案:

答案 0 :(得分:2)

此客户端代码最终正常运行:

exports.handler = function(context, event, callback) {
  const client = context.getTwilioClient();
  const ClientCapability = require('twilio').jwt.ClientCapability;
  const response = new Twilio.Response();
  response.appendHeader('Access-Control-Allow-Origin', '*');
  response.appendHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  response.appendHeader('Access-Control-Allow-Headers', 'Content-Type');
  response.appendHeader('Content-Type', 'application/json');
  let identity = "sampleIdentity";
  const capability = new ClientCapability({
    accountSid: context.ACCOUNT_SID,
    authToken: context.AUTH_TOKEN
  });
  capability.addScope(new ClientCapability.IncomingClientScope(identity));
  capability.addScope(new ClientCapability.OutgoingClientScope({
    applicationSid: context.TWILIO_TWIML_APP_SID
  }));
  response.setBody({identity: identity, token: capability.toJwt()})
  console.log(capability.toJwt());
  callback(null, response);
};

答案 1 :(得分:1)

Twilio开发者传道者在这里。

我很高兴看到K. Rhoda解决了这个问题。我只是想明白是什么让它发挥作用。

您可以从功能中的Twilio.Response访问custom response。响应初始化如下:

const response = new Twilio.Response();

然后有以下有用的方法:

// set the body of the response
response.setBody(body);

// set a header for the response
response.appendHeader(key, value);

// set all the headers for the response
response.setHeaders(obj);

// set the status code for the response
response.setStatusCode(200);

然后您可以使用回调函数发送该响应,如下所示:

callback(null, response);

答案 2 :(得分:0)

就我而言,上述所有操作均无法正常进行,因为我已默认选中“ 检查有效的Twilio签名”并发出了没有签名的请求。

在我取消选中它之后,以上答案起作用了。因此,请注意是否已选中此选项以及是否已正确签名。