Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Request how to send multipart/form-data POST request

I'm trying to send a POST request to an API with an image in the request. I'm doing this with the request module but everything I try it isn't working. My current code:

const options = {
    method: "POST",
    url: "https://api.LINK.com/file",
    port: 443,
    headers: {
        "Authorization": "Basic " + auth,
        "Content-Type": "multipart/form-data"
    },
    form : {
        "image" : fs.readFileSync("./images/scr1.png")
    }
};

request(options, function (err, res, body) {
    if(err) console.log(err);
    console.log(body);
});

But request uses Content-Type: application/x-www-form-urlencoded for some reason... How can I fix this?

like image 895
Paul de Koning Avatar asked Mar 01 '18 15:03

Paul de Koning


People also ask

How do you send a POST request in node JS?

Example code: var request = require('request') var options = { method: 'post', body: postData, // Javascript object json: true, // Use,If you are sending JSON data url: url, headers: { // Specify headers, If any } } request(options, function (err, res, body) { if (err) { console. log('Error :', err) return } console.

How multipart form data is sent?

Multipart form data: The ENCTYPE attribute of <form> tag specifies the method of encoding for the form data. It is one of the two ways of encoding the HTML form. It is specifically used when file uploading is required in HTML form. It sends the form data to server in multiple parts because of large size of file.


1 Answers

As explained in documentation form multipart/form-data request is using form-data library. So you need to supply formData option instead of form option.

const options = {
    method: "POST",
    url: "https://api.LINK.com/file",
    port: 443,
    headers: {
        "Authorization": "Basic " + auth,
        "Content-Type": "multipart/form-data"
    },
    formData : {
        "image" : fs.createReadStream("./images/scr1.png")
    }
};

request(options, function (err, res, body) {
    if(err) console.log(err);
    console.log(body);
});
like image 60
Ivan Vasiljevic Avatar answered Sep 19 '22 16:09

Ivan Vasiljevic