0

我正在尝试运行为 IoT 中心创建 SAS 令牌的 nodejs 函数。但是,在运行代码时,函数会崩溃并出现以下异常:

2016-06-23T19:01:24.415 Exception while executing function: Functions.getSASToken. mscorlib: TypeError: f.apply is not a function
    at eval (eval at <anonymous> (C:\Program Files (x86)\SiteExtensions\Functions\0.2.10238\bin\edge\double_edge.js:34:28), <anonymous>:42:7).

我正在尝试运行的函数是 Microsoft 发布的 SAS 令牌生成器,我只对其进行了调整以运行 Functions:

var crypto = require('crypto');
var util = require('util');

var sbNamespace = process.env.SBNAMESPACE || 'xxx.azure-devices.net';

var generateSasToken = function(resourceUri, signingKey, policyName, expiresInMins) {
    resourceUri = encodeURIComponent(resourceUri.toLowerCase()).toLowerCase();

    // Set expiration in seconds
    var expires = (Date.now() / 1000) + expiresInMins * 60;
    expires = Math.ceil(expires);
    var toSign = resourceUri + '\n' + expires;

    // using crypto
    var decodedPassword = new Buffer(signingKey, 'base64').toString('binary');
    const hmac = crypto.createHmac('sha256', decodedPassword);
    hmac.update(toSign);
    var base64signature = hmac.digest('base64');
    var base64UriEncoded = encodeURIComponent(base64signature);

    // construct autorization string
    var token = "SharedAccessSignature sr=" + resourceUri + "&sig="
    + base64UriEncoded + "&se=" + expires;
    if (policyName) token += "&skn="+policyName;
    // console.log("signature:" + token);
    return token;
};

module.exports.getSASToken = function getSASToken(context, req) { 
    var token = req.query.token;
    var deviceId = req.query.deviceId;
    var resourceUri = util.format('%s/devices/%s', sbNamespace, deviceId);

    var sasToken = generateSasToken(resourceUri, token, null, 14400);

    context.log(sasToken);
    context.send(sasToken);    
}
4

1 回答 1

3

问题是函数期望您的代码导出一个未命名的函数。因此,删除getSASToken名称,您应该会很好。即,改变:

module.exports.getSASToken = function getSASToken(context, req) {
    ...
}

module.exports = function getSASToken(context, req) {
    ...
}
于 2016-06-25T13:35:44.667 回答