Skip to content

Using fetch api with Readable #4137

@hikarunoryoma

Description

@hikarunoryoma

Details

I'm really excited about Node.js natively supporting a fetch API. Previously I have used node-fetch and form-data for sending content with contentType multipart/form-data. In my use case I have been grabbing an AWS s3 object and sending that file in my request. I'm having trouble doing this with the native fetch API. I noticed that AWS has started to support transforming their GetObjectBody to byteArrays or WebStreams, but unsure how to leverage these.

My thinking is that I would append formdata like the following: formData.append("attachments", new Blob([await s3Object.Body.transormToByteArray()]), but this appears to time out.

Node.js version

18.5.0

Example code

// This used to work:
import FormData from "form-data"; // would like to use Node.JS FormData
import fetch from "node-fetch"; // would like to use Node.JS fetch

const s3Client = new S3Client({});
const formData = new FormData();

// This is a PDF file
const s3Object = await s3Client.send(
  new GetObjectCommand({
    Bucket: BUCKET_NAME,
    Key: BUCKET_KEY,
  })
);
// Would expect to change the following line to:
// formData.append("attachments", new Blob([await s3Object.Body.transormToByteArray()])
formData.append("attachments", s3Object.Body);

const response = await fetch(API_URL, {
  method: "POST",
  headers: {
    Authorization: API_KEY,
    ContentType: "multipart/form-data",
  },
  body: formData,
});

Operating system

Linux

Scope

fetch API

Module and version

fetch

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions