簡體   English   中英

AWS Lambda中的HTTP請求

[英]HTTP Requests in an AWS Lambda

我是Lambdas的新手所以也許還有一些我還沒有抓到的東西,但是我已經編寫了一個簡單的Lambda函數來向外部網站發出HTTP請求。 出於某種原因,無論我使用Node的http還是https模塊,我都會獲得ECONNREFUSED

這是我的Lambda:

var http = require('http');

exports.handler = function (event, context) {
    http.get('www.google.com', function (result) {
        console.log('Success, with: ' + result.statusCode);
        context.done(null);
    }).on('error', function (err) {
        console.log('Error, with: ' + err.message);
        context.done("Failed");
    });
};

這是日志輸出:

START RequestId: request hash
2015-08-04T14:57:56.744Z    request hash                Error, with: connect ECONNREFUSED
2015-08-04T14:57:56.744Z    request hash                {"errorMessage":"Failed"}
END RequestId: request hash

是否需要執行HTTP請求的角色權限? Lambda甚至允許普通的舊HTTP請求嗎? 我需要設置特殊標頭嗎?

任何指導表示贊賞。

我解決了自己的問題。

顯然,如果您決定將URL作為第一個參數提供給.get() ,則必須在URL前面加上http:// ,例如http://www.google.com

var http = require('http');

exports.handler = function (event, context) {
  http.get('http://www.google.com', function (result) {
    console.log('Success, with: ' + result.statusCode);
    context.done(null);
  }).on('error', function (err) {
    console.log('Error, with: ' + err.message);
    context.done("Failed");
  });
};

或者,您可以將第一個參數指定為選項哈希值 ,其中hostname可以是URL的簡單形式。 例:

var http = require('http');

exports.handler = function (event, context) {
  var getConfig = {
    hostname: 'www.google.com'
  };
  http.get(getConfig, function (result) {
    console.log('Success, with: ' + result.statusCode);
    context.done(null);
  }).on('error', function (err) {
    console.log('Error, with: ' + err.message);
    context.done("Failed");
  });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM