How do I post form data with fetch api?
To quote MDN on FormData
(emphasis mine):
The
FormData
interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using theXMLHttpRequest.send()
method. It uses the same format a form would use if the encoding type were set to"multipart/form-data"
.
So when using FormData
you are locking yourself into multipart/form-data
. There is no way to send a FormData
object as the body and not sending data in the multipart/form-data
format.
If you want to send the data as application/x-www-form-urlencoded
you will either have to specify the body as an URL-encoded string, or pass a URLSearchParams
object. The latter unfortunately cannot be directly initialized from a form
element. If you don’t want to iterate through your form elements yourself (which you could do using HTMLFormElement.elements
), you could also create a URLSearchParams
object from a FormData
object:
const data = new URLSearchParams();
for (const pair of new FormData(formElement)) {
data.append(pair[0], pair[1]);
}
fetch(url, {
method: 'post',
body: data,
})
.then(…);
Note that you do not need to specify a Content-Type
header yourself.
As noted by monk-time in the comments, you can also create URLSearchParams
and pass the FormData
object directly, instead of appending the values in a loop:
const data = new URLSearchParams(new FormData(formElement));
This still has some experimental support in browsers though, so make sure to test this properly before you use it.
how do I post form data and upload file with the JS fetch API
No need to transform to JSON, and no need to use entries()
on FormData. Also check the spelling, you wrote formdata
which is different than formData
.
const thisForm = document.getElementById('signup');
var formData = new FormData(thisForm);
const profile = document.getElementById('profile');
formData.append("profile", profile.files[0]);
const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
});
How to POST a simple formdata using fetch API?
I fixed my problem by adding missing Content-Type
and JSON.stringify
:
await fetch("https://api.factarni.tn/article/create", {
method: "POST",
body: JSON.stringify({
code: `1`,
article: `porte`,
price: 12,
vat: null,
status: 1,
company_id: 10,
}),
headers: {
"Content-Type": "application/json",
Authorization:
"eyJhbGciOiJSUzI1NiIsImtpZC...
},
});
How do I POST with multipart form data using fetch?
You're setting the Content-Type
to be multipart/form-data
, but then using JSON.stringify
on the body data, which returns application/json
. You have a content type mismatch.
You will need to encode your data as multipart/form-data
instead of json
. Usually multipart/form-data
is used when uploading files, and is a bit more complicated than application/x-www-form-urlencoded
(which is the default for HTML forms).
The specification for multipart/form-data
can be found in RFC 1867.
For a guide on how to submit that kind of data via javascript, see here.
The basic idea is to use the FormData object (not supported in IE < 10):
async function sendData(url, data) {
const formData = new FormData();
for(const name in data) {
formData.append(name, data[name]);
}
const response = await fetch(url, {
method: 'POST',
body: formData
});
// ...
}
Per this article make sure not to set the Content-Type
header. The browser will set it for you, including the boundary
parameter.
How to send and receive formData through fetch to node and express?
Content-Type
You aren't sending a FormData object. You are sending JSON.
You are passing a string to the body
property so you need to explicitly say that you are sending JSON. fetch
cannot infer that your string is JSON.
This step wouldn't be needed if you were sending multipart form data by passing a FormData object, nor if you were sending URL Encoded data by passing a URLSearchParams object. fetch
can infer the content-type from those objects.
await fetch(`/dbControl/editQuestion?id=${id}`, {
method: "POST",
body: JSON.stringify(dataToSend),
headers: {
"Content-Type": "application/json"
}
});
Body Parsing Middleware
As per the documentation:
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().
… you need to include some body parsing middleware.
app.use(express.json());
(And do it before you register the end point handler).
Using FormData() inside fetch api is not working
You shouldn't set the Content-Type
header to application/json
if you're not sending json. According to this answer, you don't need to set the Content-Type
header.
body data type must match "Content-Type" header
Using Fetch
How to handle Fetch api formData submit using expressJS
Maybe you can try this code below:
In Your Fetch API:
submit.addEventListener('click', ()=> {
let fname = document.querySelector('#fname').value;
let lname = document.querySelector('#lname').value;
let email = document.querySelector('#email').value;
let gender = document.querySelector('#gender').value;
let formData = { fname, lname, email, gender };
fetch('http://localhost:5000/api/members', {
method: 'POST',
body: JSON.stringify(formData),
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
});
});
You can read the documentation here.
Now, you can console.log()
it first.
app.post('/api/members', (req, res)=> {
console.log(req.body);
// do some stuff here
});
I hope it's can help .
How can I POST a form data in JSON format using fetch API without using JQuery?
FormData
does not create a regular object, but an iterable object which does not expose its values. You can only get the values from a FormData
instance by either looping over it with for...of
or by using the get()
or getAll()
methods.
So if you really need JSON, then you should write a helper function that creates an object, loops over the FormData
instance and assigns the keys in the object to its corresponding value.
Then return the result stringified and you've got yourself some JSON.
const formDataToJSON = formData => {
if (!(formData instanceof FormData)) {
throw TypeError('formData argument is not an instance of FormData');
}
const data = {}
for (const [name, value] of formData) {
data[name] = value;
}
return JSON.stringify(data);
}
async function postFormDataAsJson({ url, formData }) {
const formDataJsonString = formDataToJSON(formData);
...
Note: This does not work when the formData
object contains complex values like Blob
or File
.
Posting Form Data in Javascript with Fetch - Bug
Assuming this button is in a form
, I think you need to add preventDefault()
for the click event otherwise the form will submit and refresh the page. Also, fix the second console.log
because that was breaking my tests until I noticed it as well.
async function save_background_picture(e){
e.preventDefault();
// ...rest of the code
console.log("test 2"); // <--- needed quotes
}
Sent Post Request with Body Form Data with fetch()
The above error is commonly caused due to mismatch of content-type between what was supplied by fetch method and that expected by the server API.
In the above code, the fetch method is sending content of the type 'aplpication/json'.
If the server is throwing an error for this format, it can be concluded that the server is probably expecting content in a different format.
The valid content-type formats supported are:
- application/json (Not working in the current scenario)
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain
Therefore, the problem may be solved by changing the 'content-type' header in the fetch call from 'application/json' to one of these other supported types.
An example of working fetch call:
const data = new FormData();
data.append('client_id', 'lorem ipsum');
data.append('client_secret', 'lorem ipsum');
data.append('scope', 'lorem ipsum');
data.append('grant_type', 'lorem ipsum');
fetch(apiUrl, {
method: "POST",
headers: {
// "Content-Type": "application/json" --> option 1 (not working)
// "Content-Type": "application/x-www-form-urlencoded" --> option 2
// "Content-Type": "multipart/form-data" --> option 3
// "Content-Type": "text/plain" --> option 4
},
body: data
})
// Option 5: Try fetch without any header
fetch(apiUrl, {
method: "POST",
body: data
})
More information:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Related Topics
Where to Write to Localstorage in a Redux App
JavaScript - How to Extract Filename from a File Input Control
How to Extract the Hostname Portion of a Url in JavaScript
JavaScript - Get Minutes Between Two Dates
Recursive Matching with Regular Expressions in JavaScript
Checking If Jquery Is Loaded Using JavaScript
What Is Ajax and How Does It Work
How to Extend Function with Es6 Classes
Http Ajax Request via Https Page
JavaScript Variables Declare Outside or Inside Loop
What's the Difference Between Window.Location= and Window.Location.Replace()
Can a PDF File's Print Dialog Be Opened with JavaScript
Optional Chaining in JavaScript
Rails - Could Not Find a JavaScript Runtime