lambda函数内部的ajax调用不起作用

时间:2017-05-19 18:00:46

标签: lambda

我有一个lambda函数,我试图通过ajax调用调用外部服务并返回结果,然后在lambda的return函数中返回reult。这是我的代码:

console.log('Loading function');

exports.handler =  (event, context, callback) => {
var token = event.authorizationToken;
 var http = require('https');
           var url = "https://jsonplaceholder.typicode.com/posts";

switch (token.toLowerCase()) {
    case 'allow':


        var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() { 
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
        callback(null, generatePolicy('user', 'Allow', event.methodArn,xmlHttp.responseText[0].title));
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous 
xmlHttp.send(null);

        break;

    default:
        callback("Error: Invalid token"); 
 }
};

var generatePolicy = function(principalId, effect, resource,res) {
var authResponse = {};

authResponse.principalId = principalId;
if (effect && resource) {
    var policyDocument = {};
    policyDocument.Version = '2012-10-17'; // default version
    policyDocument.Statement = [];
    var statementOne = {};
    statementOne.Action = 'execute-api:Invoke'; // default action
    statementOne.Effect = effect;
    statementOne.Resource = resource;
    policyDocument.Statement[0] = statementOne;
    authResponse.policyDocument = policyDocument;
}

// Can optionally return a context object of your choosing.
authResponse.context = {};
authResponse.context.stringKey = res;
return authResponse;

}

当我尝试上面的代码时,我收到以下错误:

ReferenceError: XMLHttpRequest is not defined

显然lambda不支持XMLHttpRequest或ajax。 有什么方法可以进行ajax调用并在lambda中获得响应(优选在json中)?

1 个答案:

答案 0 :(得分:0)

Lambda当然支持XMLHttpRequest! :)

您只需要安装它:

npm i xmlhttprequest

然后在lambda函数中导入它:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var xhr = new XMLHttpRequest();