我尝试使用aws-api-gateway-client模块从NodeJS调用AWS api网关。
这是我的代码:
module.exports = function(app) {
var apigClientFactory = require('aws-api-gateway-client').default;
var querystring = require('querystring');
var apigClient = apigClientFactory.newClient({
apiKey: '1234'
});
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'
};
var additionalParams = {};
app.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
app.post("/customerinfo", function(req, res) {
console.log("name: " + req.body["customer_name"]);
var body = {"async": true,
"crossDomain": true,
"url": "https://mystuff.execute-api.us-west-2.amazonaws.com/staging/api",
"method": "POST",
"headers": {
"cache-control": "no-cache"
},
"data": querystring.stringify(req.body["customer_name"])
};
apigClient.invokeApi(params, body, additionalParams)
.then(function(result){
// Add success callback code here.
}).catch( function(result){
// Add error callback code here.
});
});
};
一旦启动节点服务器,我就会收到此错误:
/Users/eugene/Desktop/dms/node_modules/aws-api-gateway-client/dist/apigClient.js:84
var endpoint = /(^https?:\/\/[^\/]+)/g.exec(invokeUrl)[1];
^
TypeError: Cannot read property '1' of null
at Object.apigClientFactory.newClient (/Users/eugene/Desktop/dms/node_modules/aws-api-gateway-client/dist/apigClient.js:84:57)
at module.exports (/Users/eugene/Desktop/dms/app/routes.js:7:40)
at Object.<anonymous> (/Users/eugene/Desktop/dms/server.js:26:24)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.runMain [as _onTimeout] (module.js:441:10)
at Timer.listOnTimeout (timers.js:92:15)
从Node调用AWS Api Gateway的正确方法是什么?
答案 0 :(得分:2)
当您在代码中调用网关客户端工厂的'newClient'方法时:
var apigClient = apigClientFactory.newClient({
apiKey: '1234'
});
它期望配置对象中的键'invokeUrl'。因此,您需要将此键与指定的URL一起作为此键的值传递。例如:你应该试试这个 -
var apigClient = apigClientFactory.newClient({
apiKey: '1234',
invokeUrl:'https://xxxxx.execute-api.us-east-1.amazonaws.com'
});
希望,它可以帮助您解决此问题。
答案 1 :(得分:0)
在另一条路径上,为什么不直接将API-Gateway的API作为休止调用?只需调用api网址,然后在标头中将密钥作为“ x-api-key”传递即可。这将使事情变得简单而容易被其他开发人员理解。