ralfe
ralfe

Reputation: 1454

How to POST JSON + pdf file with Unirest in NodeJS

In NodeJS I am trying to POST JSON data to the server along with a file using the following code:

unirest.post(url)
.headers(headers)
.send(data)
.attach('file', file)
.end(function (response) {
    var statusCode = response.status;
    if (statusCode != 200) {
        console.log("Result: ", response.error);
    }
});

However, on the server, I am only receiving the file, and not the JSON object from .send(data). I see there is a .multipart() function I can use, but I'm not sure how best to use this?

Upvotes: 2

Views: 1323

Answers (1)

Gurbakhshish Singh
Gurbakhshish Singh

Reputation: 1064

When you send JSON data over http, content type is application/json. when you send files over http, content type is multipart/form-data. You can send form fields while sending a multipart request but you can't send JSON data in multipart request. You have 2 options to send this request

  1. While using multipart/form-data, Stringify you JSON data and send it as a form field and parse it on other end
  2. While using application/json, Base64 you file and send it as a property in your JSON data

Upvotes: 3

Related Questions