2017-06-03 74 views
0

我想使用aws-api-gateway-client模塊從NodeJS調用AWS api網關。如何從節點正確調用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) 

什麼是從節點調用AWS API網關的正確方法?

回答

1

當你調用「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' 
}); 

希望,它可以幫助你解決這個問題。