简体   繁体   English

使用本机 NodeJS 中的提取将文件上传到 REST API

[英]Upload file to a REST API using fetch in native NodeJS

I'm trying to use the native fetch() API in NodeJS to upload a file to a REST API. So far, I've made other GET and POST requests successfully, but this file upload is causing me a lot of trouble.我正在尝试使用 NodeJS 中的本机 fetch() API 将文件上传到 REST API。到目前为止,我已经成功地发出了其他 GET 和 POST 请求,但是这个文件上传给我带来了很多麻烦。

I have the following function -我有以下 function -

async function uploadDocumentToHub(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);
}

which I then run with the following code -然后我用下面的代码运行 -

async function async_main() {
  ......
.......
  await uploadDocumentToHub(hub_entity_id, document_path);
}

// main();
async_main();

And I keep getting the following error -而且我不断收到以下错误 -

node:internal/deps/undici/undici:5536
          p.reject(Object.assign(new TypeError("fetch failed"), { cause: response.error }));
                                 ^

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

I'm baffled about what's going on and what this error is about.我对发生的事情以及此错误的含义感到困惑。 Any ideas?有任何想法吗? The following code correctly uploads the file (auto-generated from postman, some data <removed> for security) -以下代码正确上传文件(从 postman 自动生成,一些数据 <removed> 为了安全) -

var axios = require('axios');
var FormData = require('form-data');
var fs = require('fs');
var data = new FormData();
data.append('type', 'Document');
data.append('name', 'ap_test_document.pdf');
data.append('file', fs.createReadStream('kX3bdHb1G/ap_test_document.pdf'));
data.append('entity_object_id', '<id>');

var config = {
  method: 'post',
  url: '<url>',
  headers: { 
    'Authorization': '<token>', 
    ...data.getHeaders()
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

Some help would be much appreciated.一些帮助将不胜感激。

Thanks!谢谢!

You can't use the fetch API in Node.js, either you can install axios or node-fetch .您不能在 Node.js 中使用fetch API,您可以安装axiosnode-fetch

import fetch from 'node-fetch';

const body = {a: 1};

const response = await fetch('https://httpbin.org/post', {
    method: 'post',
    body: JSON.stringify(body),
    headers: {'Content-Type': 'application/json'}
});
const data = await response.json();

console.log(data);```

https://www.npmjs.com/package/node-fetch
https://www.npmjs.com/package/axios

You can append a file to the Node 18 native Fetch by reading the file with fs.readFile and converting the contents to a Blob .您可以通过使用fs.readFile读取文件并将内容转换为Blob来将文件 append 发送到 Node 18 本机 Fetch。

The following is some pseudo-code I whipped up in TypeScript (YMMV):以下是我在 TypeScript (YMMV) 中编写的一些伪代码:

import fs from 'fs/promises';

async function createBlobFromFile(path: string): Promise<Blob> {
    const file = await fs.readFile(path);
    return new Blob([file]);
}

const path = '/path/to/file.txt';
const formData = new FormData();
formData.append('file', await createBlobFromFile(path), 'file.txt');

const response = await fetch('https://some.url', {
    method: 'POST',
    body: formData
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM