Posting form data with function

I'm trying to post a form to a service that receives 2 pieces of data, but for some reason the function for form data isn't working.

This is the function I have so far:

var payload = msg.payload;

var data = { 'url': payload.content,'format': 'bestvideo' };

msg.headers = {
'content-type':'application/x-www-form-urlencoded',
'boundary':'63c5979328c44e2c869349443a94200e'
}
msg.payload = {JSONString : JSON.stringify(data)}
return msg;

And the msg.payload returns what I expect as data:

{"url":"https://www.youtube.com/watch?v=oY6_DSuYFg4","format":"bestvideo"}

But my service returns an error saying that URL was not received.
What am I missing?

Since you have given us no clue about node red interfaces with the service it is impossible to say.

you're right, I should have given more detail.

Right now, the flow only uses the function interface, with the code above and the http-request where I only set the method to POST and the URL.

Hi @brunoamaral the challenge is more that we don't know what the service API you are calling expects in terms of how you have to format the request.

As a start, I would remove the msg.headers settings and let the node encode it how it thinks it should be set.

The format of the payload is slightly unusual - you are posting a form with one property called JSONString whose value is the json encoding of the object with the url and format properties. Is that really what your service expects? Or should the body of the http request have the url and format properties at the top level? I would try setting msg.payload = data and seeing what happens (again, without the msg.headers property being set so the node sets the proper default header values).

1 Like

Thank you @knolleary, that was it.

I still had to keep one of the headers, but the code below works:

var payload = msg.payload;

var data = { 'url': payload.content,'format': 'bestvideo' };

msg.headers = {
'content-type':'application/x-www-form-urlencoded'
}
msg.payload = data;
return msg;

Heartfelt thanks for providing this solution here :heart_eyes:

1 Like

Following the http request documentation this is what worked for me:

const {payload} = msg

const headers = {
'content-type':'multipart/form-data'
}

return {
    headers,
    payload: {
        image: {
            value: payload,
            options: {
                filename: 'image.jpg'
            }
        }
        
    }
}

The input of the function node is a file-read node