How can i send a form parameter in a post (JavaScript fetch()) request?
e.g.
curl --form "avatar=@me.jpg" "https://example.com/api/v4/endpoint"
I tried the folloing code:
const form = new FormData()
form.append("foo":"bar")
fetch( "https://someapi.org/api", {
method: 'POST',
headers:form
} )
.then( response => response.json() )
.then( response => {
console.log(response)
} );
}
which doesn't work for me.
The FormData should be supplied as the body property of the RequestInit, like this:
Make sure you use the correct
Content-Typeheader. You can read about UsingFormDataObjects on MDN.
so-70865955.ts:
async function example () {
const form = new FormData();
form.append("foo", "bar");
const apiAddress = "https://someapi.org/api";
const init: RequestInit = {
method: 'POST',
headers: new Headers([['content-type', 'application/x-www-form-urlencoded']]),
body: form,
};
const response = await fetch(apiAddress, init);
const data = await response.json();
console.log(data);
}
// Invoke it
example();
In your console:
deno run --allow-net so-70865955.ts