通过POST请求上载文件时,NodeJS获取失败(对象2不可迭代)

68de4m5k  于 2023-02-03  发布在  Node.js
关注(0)|答案(1)|浏览(160)

bounty将在6天后过期。回答此问题可获得+500的声誉奖励。DanHabib正在寻找来自声誉良好来源的答案github.com/vercel/community/discussions/1426在此添加了更多上下文!

我尝试在NodeJS中使用本机提取上传一个文件(在节点17.5中添加,请参见https://nodejs.org/ko/blog/release/v17.5.0/)。
但是,我一直收到以下错误-

TypeError: fetch failed
at Object.processResponse (node:internal/deps/undici/undici:5536:34)
at node:internal/deps/undici/undici:5858:42
at node:internal/process/task_queues:140:7
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
cause: TypeError: object2 is not iterable
at action (node:internal/deps/undici/undici:1660:39)
at action.next (<anonymous>)
at Object.pull (node:internal/deps/undici/undici:1708:52)
at ensureIsPromise (node:internal/webstreams/util:172:19)
at readableStreamDefaultControllerCallPullIfNeeded
node:internal/webstreams/readablestream:1884:5)
at node:internal/webstreams/readablestream:1974:7
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

我使用下面的代码创建并提交表单响应-

function upload(hub_entity_id, document_path) {
  let formData = new FormData();
  formData.append("type", "Document");
  formData.append("name", "ap_test_document.pdf");
  formData.append("file", fs.createReadStream("ap_test_document.pdf"));
  formData.append("entity_object_id", hub_entity_id);

  const form_headers = {
    Authorization: auth_code,
    ...formData.getHeaders(),
  };

  console.log(
    `Uploading document ap_test_document.pdf to hub (${hub_entity_id}) `
  );
  console.log(formData);

  let raw_response = await fetch(urls.attachments, {
    method: "POST",
    headers: form_headers,
    body: formData,
  });

  console.log(raw_response);
}
xuo3flqw

xuo3flqw1#

使用fs.readFileSync而不是创建读取流
表格数据.append(“文件”,文件系统.readFileSync(“ap_test_document.pdf”));
你也可以在formData.append中直接使用文件名
表格数据.append(“文件”,fs.readFileSync(“测试文件”),“测试文件”);

相关问题