Server-side action problem when using fetch to HTTPS site

I’m building a server-side action for a plugin I’m writing, in which I need send a POST request to an API.
The way I do it is, roughly like this:

function(properties, context) {
    const fetch = require("node-fetch");
    const body = {a: 1};
    const result = fetch("https://some.random.api.com/v3.5/print/", {
        method: "POST",
        headers: {
            Accept: "application/json",
            Authorization: context.keys["API Key"],
            "Content-Type": "application/x-www-form-urlencoded"
	    },
        body: JSON.stringify(body)
    }).then(response => console.log(response));
}

The request is constructed correctly. However, I can see this error in the server logs (ellipsis mine):

ERROR Unhandled Promise Rejection {“errorType”:“Runtime.UnhandledPromiseRejection”,“errorMessage”:“FetchError: request to https://some.random.api.com/v3.5/print/ failed, reason: Client network socket disconnected before secure TLS connection was established” …}

I’m a bit stuck. I guess I’m doing something fundamentally wrong here.

Hello,

It would help if you had a sync function, not async.

Please use the Bubble’s request function that you can access via context.request.

1 Like

That was it - I was completely blind to it and didn’t notice it in the help.

In case it’s of any help to others, the function I wrote in my original post would translate to something along these lines:

function(properties, context) {
    const body = {a: 1};
    const options = {
            uri: "https://some.random.api/v3.5/print/",
            method: "POST",
            headers: {
                // same as above
                "Content-Type": "application/x-www-form-urlencoded" // must specify this
            },
            body: JSON.stringify(body)
        };
    const response = context.request(options);
    console.log(response);
}
4 Likes