2

我正在尝试发出 POST 请求以将二进制文件上传到服务器,但表单数据未正确发送(或根本未发送)。

我目前将 node-fetch 与 puppeteer 的集成适用于 POST 或 GET 请求{"Content-Type": "application/json"}

这是我的代码:

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);
    }
  });
}

这是表单数据的发送方式:
在此处输入图像描述

这就是发送的方式:
在此处输入图像描述

此外,发送的内容长度只有 15 个字节,应该在 2mb 左右。

我是否正确使用表单数据和节点获取?

谢谢!

4

0 回答 0