响应未定义 - aws-api-gateway-client

时间:2018-03-04 08:13:57

标签: node.js amazon-web-services aws-api-gateway

我创建了一个AWS API网关来调用Lambda函数来生成随机数:

Lambda函数:

exports.handler = (event, context, callback) => {
let min = parseInt(event.min);
let max = parseInt(event.max);
let generatedNumber = Math.floor(Math.random() * max) + min;
context.done(null, {generatedNumber: generatedNumber});
};

用于get方法的API网关中的正文映射模板:

{
    "min" : $input.params('min'),
    "max" : $input.params('max')
}

当我访问API端点时,如下所示: https://abcdefgh.execute-api.ap-south-1.amazonaws.com/DEV/number?min=10&max=20

我得到了正确的答复:

{"generatedNumber":28}

但是当我尝试使用aws-api-gateway-client访问node.js中的API时,我收到以下响应:



_currentUrl: 'https://abcdefgh.execute-api.ap-south-1.amazonaws.com/DEV/number' },
  response: undefined




当前网址应设置为' https://abcdefgh.execute-api.ap-south-1.amazonaws.com/DEV/number?min=20&max=40'但它被设置为' https://abcdefgh.execute-api.ap-south-1.amazonaws.com/DEV/number'。

这是我的node.js代码,用于访问此API:



let AWS = require('aws-sdk');
AWS.config.loadFromPath('./config.json');
//AWS.config.region = 'ap-south-1';
let lambda = new AWS.Lambda();
let apigClientFactory = require('aws-api-gateway-client').default;
let config = {
    invokeUrl: 'https://abcdefgh.execute-api.ap-south-1.amazonaws.com/DEV',
    accessKey: '<access-key>',
    secretKey: '<secret-key>',
    region: 'ap-south-1'
};
let apigClient = apigClientFactory.newClient(config);
let apiParams = '{"min": 20,"max": 40}';
let body = {
    
}

let additionalParams = {
   
}
apigClient.invokeApi(apiParams, '/number', 'GET', additionalParams, body)
    .then(function (result) {
        console.log(result);
    })
    .catch(function (error) {
        console.log(error);
    });
&#13;
&#13;
&#13;

我尝试将apiParams更改为:

let apiParams = {"min": 20,"max": 40};

我收到以下错误: '{"message": "Could not parse request body into json: Unexpected character (\\\',\\\' (code 44)): expected a value\\n at [Source: [B@42feb146; line: 2, column: 14]"}' } } 我的代码出了什么问题?

提前致谢

2 个答案:

答案 0 :(得分:0)

尝试修改映射模板:

{
    "min" : "$input.params('min')",
    "max" : "$input.params('max')"
}

来源:input-variable-reference

答案 1 :(得分:0)

我发现了问题。我需要在additionalParmae​​ters对象中传递参数,如:

let additionalParams = {
   queryParams: {
   min: 20, max: 40
   }
}

但文字

var params = {
    //This is where any header, path, or querystring request params go. The key is the parameter named as defined in the API
    userId: '1234',
};

是误导性的,因为当参数被添加到params对象时可能没有传递查询参数(可能是对我来说),但是只有在传递给AdditionalPrams时才传递。

希望它有所帮助。