Ahmed Ghoneim
Ahmed Ghoneim

Reputation: 164

Browser forcibly sending multipart/formdata

I'm sending a post request from the browser using the fetch API. This is my code:

const headers = new Headers();
headers.append("Content-Type", "application/x-www-form-urlencoded");

fetch('/signup', {
  method: 'POST',
  body: new FormData(document.querySelector('form')),
  credentials: 'same-origin',
  headers
}).then(
  response => response.text()
).then(
  text => console.log(text)
);

My form contains text, email and password input types only. I was expecting the form data to be sent with the content-type application/x-www-form-urlencoded, however it's getting sent as multipart/formdata.

I have tried manually setting the headers on the fetch request and explicitly specifying the encType property of the form (even though it should be url-encoded by default) but it's not working.

This happens on both Chrome and Safari. I could easily work around this by using JSON, but I really want to know why this happens!

Upvotes: 0

Views: 959

Answers (1)

Quentin
Quentin

Reputation: 944545

From the spec:

Switch on object's type:

FormData

Set action to an action that runs the multipart/form-data encoding algorithm, with object as form data set and with utf-8 as the explicit character encoding.

Set Content-Type to multipart/form-data;boundary=, followed by the multipart/form-data boundary string generated by the multipart/form-data encoding algorithm.

It uses multipart because you are passing a FormData object and that is what fetch does with FormData objects.


If you want to send application/x-www-form-urlencoded data then encode it that way manually or use an object that implements the URLSearchParams interface.

You shouldn't need to though. multipart/form-data is a standard, and I've never come across a form data parsing library that can't handle it. The only negative you should have is that it makes the request take up slightly more bytes.

Upvotes: 1

Related Questions