【问题标题】:Forward requests to internal service lambda AWS将请求转发到内部服务 lambda AWS
【发布时间】:2021-06-05 06:01:17
【问题描述】:

我需要将接收到的 lambda 函数的 http 请求转发到另一个 url(ECS 服务)并发回响应。

我设法通过以下代码实现了这种行为:

exports.handler = async (event) => {
    const response = {
        statusCode: 302, // also tried 301
        headers: {
            Location: 'http://ec2-xx-yy-zz-ww.us-west-x.compute.amazonaws.com:2222/healthcheck'
        }
    };
    
    return response;
};

这似乎有效,但这会将原始 url(类似于 toing.co:5500)更改为重定向的 aws url。

所以我尝试在 lambda 中创建一个异步请求,该请求将查询并返回响应:

const http = require('http');

const doPostRequest = () => {

  const data = {};

  return new Promise((resolve, reject) => {
    const options = {
      host: 'http://ec2-xx-yy-zz-ww.us-west-x.compute.amazonaws.com:5112/healthcheck',
      port: "2222",
      path: '/healthcheck',
      method: 'POST'
    };
    
    const req = http.request(options, (res) => {
      resolve(JSON.stringify(res.statusCode));
    });

    req.on('error', (e) => {
      reject(e.message);
    });
    
    //do the request
    req.write(JSON.stringify(data));

    req.end();
  });
};


exports.handler = async (event) => {
  await doPostRequest()
    .then(result => console.log(`Status code: ${result}`))
    .catch(err => console.error(`Error doing the request for the event: ${JSON.stringify(event)} => ${err}`));
};

但是我收到了一个错误的网关 (502) 错误。如何为发布请求(带有消息正文)实现一个简单的转发器?

【问题讨论】:

  • 您不会从 lambda 返回响应。 API 网关无法处理无效的 lambda 响应(statusCode*、正文)
  • 我没有使用API​​网关,这只是一个发送到需要转发的负载均衡器的请求
  • 为什么要将 HTTP 请求代理到 Lambda 中的 ECS?
  • 我在 ECS 上的不同端口上有不同的服务监听,我想读取正文,并将请求发送到应该发送的位置

标签: node.js amazon-web-services aws-lambda


【解决方案1】:

问题在于 lambda 函数的响应是纯 json 字符串而不是 html(正如 @acorbel 所指出的那样),因此负载均衡器无法处理响应,从而导致 502 错误。

解决方案是在响应中添加 http 标头和状态码:

const http = require('http')

let response = {
    statusCode: 200,
    headers: {'Content-Type': 'application/json'},
    body: ""
}

let requestOptions = {
    timeout: 10,
    host: "ec2-x-xxx-xx-xxx.xx-xx-x.compute.amazonaws.com",
    port: 2222,
    path: "/healthcheck",
    method: "POST"
    
}

let request = async (httpOptions, data) => {
    return new Promise((resolve, reject) => {
        let req = http.request(httpOptions, (res) => {
            let body = ''
            res.on('data', (chunk) => { body += chunk })
            res.on('end', () => { resolve(body) })
            
        })
        req.on('error', (e) => { 
                reject(e) 
            })
        req.write(data)
        req.end()
    })
}

exports.handler = async (event, context) => {
    try {
        let result = await request(requestOptions, JSON.stringify({v: 1}))
        response.body = JSON.stringify(result)
        return response
    } catch (e) {
        response.body = `Internal server error: ${e.code ? e.code : "Unspecified"}`
        return response
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 2019-10-26
    • 2020-02-21
    • 1970-01-01
    • 2022-01-23
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多