LemmyNet / lemmy-js-client

A javascript / typescript http and websocket client and type system for Lemmy.
GNU Affero General Public License v3.0
135 stars 56 forks source link

"uploadImage" method fails in Node.js #237

Closed silasabbott closed 7 months ago

silasabbott commented 7 months ago

When uploading an image Buffer in Node, lemmy is returning:

{
    msg: 'Multipart boundary is not found',
    files: null,
    url: undefined,
    delete_url: undefined
}

I think content-type headers are automatically set by fetch in the browser, but Node's fetch does not automatically set content-type headers and multipart boundaries when posting a form. This might be fixed by combining the headers generated by the form-data lib with user-defined headers here:

const response = await this.#fetchFunction(this.#pictrsUrl, {
    method: HttpType.Post,
    body: formData as unknown as BodyInit,
    headers: {
        ...this.#headers,
        ....formData.getHeaders()
    }
});

...or using the formData.submit method (although then you'd loose the custom fetch function).

Also important to note that form-data does not support File objects, so trying to upload an image File in Node throws:

TypeError: source.on is not a function
dessalines commented 7 months ago

You could try using https://github.com/lquixada/cross-fetch instead of node's fetch function.

If that doesn't work, could you submit a PR for this one?

silasabbott commented 7 months ago

cross-fetch worked as a workaround 🎉

Some frameworks already use custom fetch implementations for routing/caching/etc, so this solution might not work for everyone. I'll close for now, but if others are getting stuck on this we can re-open and get a permanent fix going.

dessalines commented 7 months ago

Sounds good.