I got "Function invocation failed: Incorrect function response body" error from lambda function

Hi, I’ve been following this tutorial.

Lambda function throws an error with ntl dev while it works fine without any error in the production. In the lambda function, it’s sending a POST request to Slack, using node-fetch.

Function invocation Incorrect error when I’m using ntl dev:


But Slack gets this request and actually post the message.
Screen Shot 2020-06-26 at 4.23.18 PM

In Production:
Screen Shot 2020-06-26 at 3.40.02 PM

In App.js it calls lambda function when it’s clicked on submit button:

class SlackMessage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            text: null,
            error: null,
            success: false,
        };
    }
    handleText = (e) => {
        this.setState({ text: e.target.value });
    };

    handleSubmit = (e) => {
        e.preventDefault();
        this.setState({ loading: true });
        fetch("/.netlify/functions/slack", {
            method: "POST",
            body: JSON.stringify({
                text: this.state.text,
            }),
        })
            .then((response) => {
                if (!response.ok) {
                    return response.text().then((err) => {
                        console.log(response);
                        throw err;
                    });
                }
            })
            .then(() =>
                this.setState({
                    loading: false,
                    text: null,
                    success: true,
                    error: null,
                })
            )
            .catch((err) => {
                console.log("in app.js:" + err);
                this.setState({
                    loading: false,
                    success: false,
                    error: err.toString(),
                });
            });
    };
    render() {
        const { loading, text, error, success } = this.state;
        return (
            <form onSubmit={this.handleSubmit}>
                {error && (
                    <p>
                        <strong>Error sending message : {error}</strong>
                    </p>
                )}
                {success && (
                    <p>
                        <strong>Done! Message sent to Slack</strong>
                    </p>
                )}
                <p>
                    <label>
                        Your Message: <br />
                        <textarea
                            onChange={this.handleText}
                            value={text}
                        ></textarea>
                    </label>
                </p>
                <p>
                    <button type="submit" disabled={loading}>
                        {loading
                            ? "Sending Slack Message..."
                            : "Send a Slack Message"}
                    </button>
                </p>
            </form>
        );
    }
}

And here is lambda function:

import fetch from "node-fetch";
const slackURL = process.env.SLACK_WEBHOOK_URL;

export function handler(event, context, callback) {
    if (event.httpMethod !== "POST") {
        return callback(null, {
            statusCode: 410,
            body: "Unsupported Request Method",
        });
    }
    try {
        const payload = JSON.parse(event.body);
        fetch(slackURL, {
            method: "POST",
            body: JSON.stringify({ text: payload.text }),
        })
            .then(() => {
                callback(null, { statusCode: 204 });
            })
            .catch((e) => {
                callback(null, {
                    statusCode: 500,
                    body: "Internal Server Error(in try): " + e,
                });
            });
    } catch (e) {
        callback(null, {
            statusCode: 500,
            body: 'Internal Server Error "test string": ' + e,
        });
    }
}

It’s all same with the tutorial code.
Why am I getting function invocation error in dev environment while I’m not when it’s deployed on Netlify?

Secondly, In Lambda function, when I use require to import node-fetch, It throws TypeError: o is not a function(Also with ntl dev):

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

But in this case, It throws the same error in production.
I installed encoding for this known issue. Now I guess it should install node-fetch’s dependent module during the build process(obviously since it’s in package.json) and should work as you’re using in any other js file. Thus, it should work whether you use require or import. But it’s not. There must be something I’m missing here.

Secondly, In Lambda function, when I use require to import node-fetch , It throws TypeError: o is not a function (Also with ntl dev ):

Just found that it’s node-fetch’s issue not Netlify’s

Thanks so much for the follow-up to let us know you’d figured it out!

Only the second problem has resolved. I’m still getting function invocation error with ntl dev. (please refer to first screenshot in the question)

Hey @peter-wd-1,
That function invocation error is coming from here:

Since the POST to Slack is working, and based on the error message that says there’s a problem with the response body, I would look here if you’re trying to get to the root of the error:

            .then((response) => {
                if (!response.ok) {
                    return response.text().then((err) => {
                        console.log(response);
                        throw err;
                    });
                }
            })

Maybe response.text should be response.body? Maybe an issue with error handling within the error? I might just console.log the whole response if !response.ok to see if it turns up anything obvious.

Hi @jen,
I have solved this issue and asked PR here. It’s a bug that occurred during validation process of the request body.

1 Like

Amazing, we love PRs! Thanks so much for doing that and for reporting back.

No problem! Please keep doing awesome works that you guys doing now :slight_smile:

1 Like