简体   繁体   English

将请求转发到内部服务 lambda AWS

[英]Forward requests to internal service lambda AWS

I need to forward a http request recieved to a lambda function to another url (ECS service) and send back the response. I need to forward a http request recieved to a lambda function to another url (ECS service) and send back the response.

I manage to achieve this behaviour with the following code:我设法使用以下代码实现此行为:

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;
};

It seems to work, but this changes the original url (which is like toing.co:5500) to the redirected aws url.它似乎有效,但这会将原来的 url(类似于 toing.co:5500)更改为重定向的 aws url。

So I tried to create an async request inside lambda that would query and return the response:因此,我尝试在 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}`));
};

but I get a bad gateway (502) error for this.但我得到了一个错误的网关(502)错误。 How can I implment a simple forwarder for post requests (with a message body)?如何为发布请求(带有消息正文)实现一个简单的转发器?

The issue was that the response from the lambda function was a plain json string and not html (as pointed out by @acorbel), hence the load balancer could not process the response, resulting in a 502 error. The issue was that the response from the lambda function was a plain json string and not html (as pointed out by @acorbel), hence the load balancer could not process the response, resulting in a 502 error.

The solution was to add http headers and a status code to the response:解决方案是在响应中添加 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM