4

I'm trying to make a POST request to upload a binary to a server and the form data is not being sent correctly (or at all).

My current integration of node-fetch with puppeteer works fine for POST or GET requests with {"Content-Type": "application/json"}.

Here is my code:

const FormData = require("form-data");
const fetch = require("node-fetch");
const fs = require("fs");

upload(pkgUrl) {
  return new Promise(async (resolve, reject) => {

    const token = ...
    const url = ...

    const stats = fs.statSync(pkgUrl);
    const fileSizeInBytes = stats.size;
    console.log("fileSizeInBytes " + fileSizeInBytes); // Prints a valid size

    const form = new FormData();
    form.append("version", "1.0");
    form.append("appFile", fs.createReadStream(pkgUrl));
    form.append("minFirmwareVersion", 8164134);
    form.append("newPackage", true);

    let headers = form.getHeaders(); 
    headers["csrf-token"] = token;

    const response = await this._makeHTTPRequest(url, "POST", headers, form);

    (...)
  });
}

_makeHTTPRequest(url, method = "GET", headers = null, body = null, parse = true) {
  return new Promise(async (resolve, reject) => {
    try {
      const response = await this._page.evaluate(async (url, method, headers, body, parse) => {
        let request = {
          method: method,
          credentials: "include"
        };

        if (headers) {
          request["headers"] = headers;
        }

        if (body) {
          request["body"] = body;
        }

        // Make request
        const fetchResponse = await fetch(url, request);

        // Return parsed (object) or plain-text response
        return parse ? await fetchResponse.json() : await fetchResponse.text();
      }, url, method, headers, body, parse);

      resolve(response);
    } catch (error) {
      reject(error);
    }
  });
}

This is how the form data should be sent:
enter image description here

And this is how is being sent:
enter image description here

Also, the content-length being sent is only 15 bytes and it should be around 2mb.

Am I using form-data and node-fetch correctly?

Thanks!

Alejandro Cotilla
  • 2,501
  • 1
  • 20
  • 35

0 Answers0