1

I am trying to use Lambda functions to fetch a webpage, and then return both the content and the response headers. Following is my code which always return "Internal server error" when triggered by Gateway API, I am confused with how to construct the response object, it dose not seem to have any document about it. Any hit is highly appreciated!

const fetch = require('node-fetch');

exports.handler = async (event) => {
    // TODO implement
    let r = await fetch('http://www.google.com');
    let buffer = await r.buffer();
    const response = {
        statusCode: r.status,
        body: buffer,
        header: r.headers
    };

    return response;
};
dovod74538
  • 113
  • 2
  • 9

1 Answers1

1

I believe your problem is that you are using the response.buffer() method. What you should be using here is the response.text() method. It will return the response body in plain text. And since the headers you are getting from the response already include the Content-Type: text/html header, you should be able to return a html document.

chjweb
  • 99
  • 1
  • 4
  • Thanks for your help. Changing it to text() does return a HTML doc, but I meant to return content types not only limited to text/html. I found there is something wrong with the line ```header: r.headers``` since the returned response does not include any header returned from the fetch. – dovod74538 Jun 04 '20 at 21:32
  • Okay, I see. It might be that the header values returned from `response.headers` are arrays. If you only need the `content-type` header, you could use `response.headers.get("content-type")`. – chjweb Jun 04 '20 at 21:40
  • Well, with further testing, it seems that I am not able to put ```buffer``` as the value of ```body```, whenever I do it, it return Internal server error, wonder if you also know the reason by any chance. thanks! – dovod74538 Jun 04 '20 at 22:32
  • I found it myself, it seems I have to return strings anyway, but can command the API Gateway to treat data as binary: https://stackoverflow.com/questions/45348580/aws-lambda-fails-to-return-pdf-file – dovod74538 Jun 04 '20 at 22:58