Search code examples
node.jsaws-lambdanode-fetch

How to use AWS Lambda to fetch a webpage and return body and headers


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

Solution

  • 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.