[javascript] How do I post form data with fetch api?

My code:

fetch("api/xxx", {
    body: new FormData(document.getElementById("form")),
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        // "Content-Type": "multipart/form-data",
    },
    method: "post",
}

I tried to post my form using fetch api, and the body it sends is like:

-----------------------------114782935826962
Content-Disposition: form-data; name="email"

[email protected]
-----------------------------114782935826962
Content-Disposition: form-data; name="password"

pw
-----------------------------114782935826962--

(I don't know why the number in boundary is changed every time it sends...)

I would like it to send the data with "Content-Type": "application/x-www-form-urlencoded", what should I do? Or if I just have to deal with it, how do I decode the data in my controller?


To whom answer my question, I know I can do it with:

fetch("api/xxx", {
    body: "[email protected]&password=pw",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
    },
    method: "post",
}

What I want is something like $("#form").serialize() in jQuery (w/o using jQuery) or the way to decode mulitpart/form-data in controller. Thanks for your answers though.

This question is related to javascript ajax fetch-api

The answer is


To add on the good answers above you can also avoid setting explicitly the action in HTML and use an event handler in javascript, using "this" as the form to create the "FormData" object

Html form :

<form id="mainForm" class="" novalidate>
<!--Whatever here...-->
</form>

In your JS :

$("#mainForm").submit(function( event ) {
  event.preventDefault();
  const formData = new URLSearchParams(new FormData(this));
  fetch("http://localhost:8080/your/server",
    {   method: 'POST',
        mode : 'same-origin',
        credentials: 'same-origin' ,
        body : formData
    })
    .then(function(response) {
      return response.text()
    }).then(function(text) {
        //text is the server's response
    });
});

?These can help you:

let formData = new FormData();
            formData.append("name", "John");
            formData.append("password", "John123");
            fetch("https://yourwebhook", {
              method: "POST",
              mode: "no-cors",
              cache: "no-cache",
              credentials: "same-origin",
              headers: {
                "Content-Type": "form-data"
              },
              body: formData
            });
            //router.push("/registro-completado");
          } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
          }
        })
        .catch(function(error) {
          console.log("Error getting document:", error);
        });

// Write Data

async function write(param) {
  var zahl = param.getAttribute("data-role");

  let mood = {
    appId: app_ID,
    key: "",
    value: zahl
  };

  let response = await fetch(web_api, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(mood)
  });
  console.log(currentMood);

// Get Data

async function get() {

  let response = await fetch(web_api + "/App/" + app_ID, {
    method: "GET",
    headers: {
      "Content-Typ": "application/jason"
    }
  });

  let todos = await response.json();

// Remove Data

function remove(id) {
  return fetch(web_api" + id, {
    method: "DELETE"
  }).then(response => {
    if (!response.ok) {
      throw new Error("Todo konnte nicht entfernt werden.");
    }
  });
}


async function removeAll() {
  let response = await fetch(web_api + "/App/" + app_ID, {
    method: "GET",
    headers: {
      "Content-Typ": "application/jason"
    }
  });
  let todos = await response.json();
  console.log(todos);

  for (let todo of todos) {
    await remove(todo.id);
  }
}

// Update Data

  function updateTodo(todo) {
return fetch(`https://__________________/api/items/${todo.id}`, {
  method: "PUT",
  body: JSON.stringify(todo),
  headers: {
    "Content-Type": "application/json",
  },
}).then((response) => {
  if (!response.ok) {
    throw new Error("Todo konnte nicht upgedated werden.");
  }
});

}


Client

Do not set the content-type header.

// Build formData object.
let formData = new FormData();
formData.append('name', 'John');
formData.append('password', 'John123');

fetch("api/SampleData",
    {
        body: formData,
        method: "post"
    });

Server

Use the FromForm attribute to specify that binding source is form data.

[Route("api/[controller]")]
public class SampleDataController : Controller
{
    [HttpPost]
    public IActionResult Create([FromForm]UserDto dto)
    {
        return Ok();
    }
}

public class UserDto
{
    public string Name { get; set; }
    public string Password { get; set; }
}

Use FormData and fetch to grab and send data

fetch(form.action, {method:'post', body: new FormData(form)});

_x000D_
_x000D_
function send(e,form) {
  fetch(form.action, {method:'post', body: new FormData(form)});

  console.log('We send post asynchronously (AJAX)');
  e.preventDefault();
}
_x000D_
<form method="POST" action="myapi/send" onsubmit="send(event,this)">
    <input hidden name="crsfToken" value="a1e24s1">
    <input name="email" value="[email protected]">
    <input name="phone" value="123-456-789">
    <input type="submit">    
</form>

Look on chrome console>network before/after 'submit'
_x000D_
_x000D_
_x000D_


To post form data with fetch api, try this code it works for me ^_^

function card(fileUri) {
let body = new FormData();
let formData = new FormData();
formData.append('file', fileUri);

fetch("http://X.X.X.X:PORT/upload",
  {
      body: formData,
      method: "post"
  });
 }

You can set body to an instance of URLSearchParams with query string passed as argument

fetch("/path/to/server", {
  method:"POST"
, body:new URLSearchParams("[email protected]&password=pw")
})

_x000D_
_x000D_
document.forms[0].onsubmit = async(e) => {_x000D_
  e.preventDefault();_x000D_
  const params = new URLSearchParams([...new FormData(e.target).entries()]);_x000D_
  // fetch("/path/to/server", {method:"POST", body:params})_x000D_
  const response = await new Response(params).text();_x000D_
  console.log(response);_x000D_
}
_x000D_
<form>_x000D_
  <input name="email" value="[email protected]">_x000D_
  <input name="password" value="pw">_x000D_
  <input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_


With fetch api it turned out that you do NOT have to include headers "Content-type": "multipart/form-data".

So the following works:

let formData = new FormData()
formData.append("nameField", fileToSend)

fetch(yourUrlToPost, {
   method: "POST",
   body: formData
})

Note that with axios I had to use the content-type.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to fetch-api

Enable CORS in fetch api Getting "TypeError: failed to fetch" when the request hasn't actually failed Fetch API request timeout? How do I post form data with fetch api? No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API Basic authentication with fetch? Trying to use fetch and pass in mode: no-cors React Native fetch() Network Request Failed Fetch: reject promise and catch the error if status is not OK? Why does .json() return a promise?