website logo

Last Updated:

Send x-www-form-urlencoded Request Using Fetch API

Browser fetch API is used to send HTTP requests to servers using Javascript. Fetch is a standard API for this task nowadays and almost replace the previous XHR API.

Many developers recommend the use of FormData interface to send form data request using Fetch. But FormData uses the same format a form would use if the encoding type were set to "multipart/form-data".

This is a problem for those who want to send a simple x-www-form-urlencoded request to the server.

In this blog, you will learn how to send a x-www-form-urlencoded request using Fetch API.

Send x-www-form-urlencoded request

Here, I encode a payload object into a form-urlencoded string and send the payload to the server.

  1. Define a payload object.
let payload = {
  name: "hrishikesh",
  email: "[email protected]",
  tag: "web-dev",
};
  1. Encode the payload using the encodeURIComponent method.
let formBody = Object.entries(payload)foer
  .map(
	([key, value]) =>
	  encodeURIComponent(key) + "=" + encodeURIComponent(value)
  )
  .join("&");
  1. Send the formBody using fetch POST request.
fetch("/api/submit", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: formBody,
});

See Also