AWS Lambda (NodeJS) 是否不允许 http.request 或 https.request



我正在尝试从 Lambda 向另一个 API 发出请求。我发现使用 NodeJS http 和 https 模块允许 GET 请求,但任何其他(例如 POST(都不起作用;巧合的是,POST是我需要为我尝试调用的服务工作的唯一方法。

以下是 Lambda 执行 GET 并接收 200 响应的工作示例:

const https = require('https')
function handler(event, context, callback) {
    const options = {
        hostname: 'encrypted.google.com'
    }
    
    https
        .get(options, (res) => {
            console.log('statusCode:', res.statusCode);
        
            res.on('end', callback.bind(null, null))
        })
        .on('error', callback);
}
exports.handler = handler

所以这证明他的请求是允许的。但是,如果脚本尝试使用 https(或 https(库/模块的.request()方法发出相同的请求,则请求永远不会完成,并且 Lambda 超时。

const https = require('https')
function handler(event, context, callback) {
    const options = {
        hostname: 'encrypted.google.com',
        method: 'GET'
    }
    
    https
        .request(options, (res) => {
            console.log('statusCode:', res.statusCode);
        
            res.on('end', callback.bind(null, null))
        })
        .on('error', callback);
}
exports.handler = handler

我不知道我做错了什么。调用https.request()静默失败 - 不会引发错误 - 并且日志中未报告任何内容。

问题是我从来没有用req.end()完成请求。

const https = require('https')
function handler(event, context, callback) {
    const options = {
        hostname: 'encrypted.google.com',
        method: 'GET'
    }
    
    https
      .request(options, (res) => {
          console.log('statusCode:', res.statusCode);
          res.on('end', callback.bind(null, null))
      })
      .on('error', callback)
      .end(); // <--- The important missing piece!
}
exports.handler = handler

如果您的 API 是 HTTPS,请尝试这个,

var url = 'HTTPS URL HERE';
var req = https.get(url, (res) => {
    var body = "";
    res.on("data", (chunk) => {
        body += chunk
    });
    res.on("end", () => {
        var result = JSON.parse(body);
        callBack(result)
    });
}).on("error", (error) => {
    callBack(err);
});
}

如果是HTTP,那么,

var url = 'HTTP URL HERE';
var req = http.get(url, (res) => {
    var body = "";
    res.on("data", (chunk) => {
        body += chunk
    });
    res.on("end", () => {
        var result = JSON.parse(body);
        callBack(result)
    });
}).on("error", (error) => {
    callBack(err);
});
}

请不要添加包要求('https'(/要求('http'(

POST 方法

请求方法完成。

这是 lambda 代码:

const https = require('https');
    
const options = {
  hostname: 'Your host name',
  path: '/api/v1/Login/Login',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body : JSON.stringify({
        'email': 'hassan.uzair9@gmail.com',
        'password': 'Asdf1234.',
  })
};
var result;
try{
    result = await https.request(options);
    console.log("result.....",result);
}catch(err){
    console.log("err......",err);
}

最新更新