Reputation: 141
I am trying to fetch this code bellow, im starting using fetch so im having some issues
import fetch, { Headers, RequestInit } from "node-fetch";
import FormData = require("form-data");
const exampleFile = fs.createReadStream(path.join(__dirname, "../lib/dummy.pdf"));
const myHeaders = new Headers();
myHeaders.append("Content-Type", "multipart/form-data");
const form = new FormData();
form.append("file", exampleFile);
const requestOptions: RequestInit = {
method: "POST",
headers: myHeaders,
body: form,
redirect: "follow"
};
await fetch(`https://api.mercadolibre.com/messages/attachments?access_token=${accessToken}`, requestOptions)
.then(response => response)
.then(result => console.log(result))
.catch(error => console.log("error", error));
but this responses this JSON (it should be just an Id for the attachment from MercadoLibre):
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
readable: true,
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: true,
_transformState: [Object],
[Symbol(kCapture)]: false
},
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
url: 'https://api.mercadolibre.com/messages/attachments?access_token=#######',
status: 400,
statusText: 'Bad Request',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
}
}
What's wrong with my code?
Upvotes: 6
Views: 15931
Reputation: 141
UPDATE: I was able to fix it by excluding the Content-Type property, allowing to fetch to detect and set the boundary and content type automatically.
The new code:
const exampleFile = fs.createReadStream(path.join(__dirname, "../lib/dummy.pdf"));
const form = new FormData();
form.append("file", exampleFile);
const requestOptions: RequestInit = {
method: "POST",
body: form
};
await fetch(`https://api.mercadolibre.com/messages/attachments?access_token=${accessToken}`, requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log("error", error));
Upvotes: 8