JavaScript Post Request – How to Send an HTTP Post Request in JS

Joel Olawanle

HTTP requests allow your front-end application to interact successfully with a back-end server or database.
One of the five popular HTTP methods for making requests and interacting with your servers is the POST method, which you can use to send data to a server.
In this article, you will learn the various methods that you can use to send an HTTP POST request to your back-end server in JavaScript. We’ll send GET requests to the free JSON Placeholder todos API for this guide.
There are two built-in JavaScript methods for making an HTTP POST request that don’t require the installation of a library or the use of a CDN. These methods are the FetchAPI, based on JavaScript promises, and XMLHttpRequest, based on callbacks.
There are other methods, such as Axios and jQuery, that you will also learn how to use.
How to Send a POST Request with the Fetch API
The FetchAPI is a built-in method that takes in one compulsory parameter: the endpoint (API URL). While the other parameters may not be necessary when making a GET request, they are very useful for the POST HTTP request.
The second parameter is used to define the body (data to be sent) and type of request to be sent, while the third parameter is the header that specifies the type of data you will send, for example JSON.
In the code above, the body holds the data to be sent to the server and added to the JSONPlaceholder todos API. Also, the headers hold the type of content you want to send to the server, which in this case is JSON data.
Note: It is always best to serialize your data before sending it to a web server or API using the JSON.stringify() method. This will help convert and ensure your JSON data is in string format.
The Fetch API is based on JavaScript promises, so you need to use the .then method to access the promise or response returned.
If this is successful, it will return the new JSON data you send to the server.
How to Send a POST Request with XMLHttpRequest
Like the Fetch API, XMLHttpRequest is also in-built and has existed much longer than the Fetch API. This means that almost all modern browsers have a built-in XMLHttpRequest object to request data from a server.
You will start by creating a new XMLHttpRequest object stored in a variable called xhr . This is important as it gives you access to all its objects using the variable.
For example, you can then open a connection with .open() , which is used to specify the request type and endpoint (the URL of the server). As you did for the FetchAPI, you will specify the type of data using the setRequestHeader method.
The next step is to create the data to be sent to the server. Make sure you serialize the data and then store it in a variable that you’ll send with the .send() method after making some checks with the .onload method.
When you put the code together, it will look like this and return the JSON data you send to the server:
The major difference between the Fetch API and XMLHttpRequest method is that the Fetch API has a better syntax that is easier to read and understand.
At this point, you have learned how to use the two JavaScript inbuilt methods to send POST HTTP requests. Let’s now learn how to use Axios and jQuery.
How to Send a POST Request with Axios
Axios is an HTTP client library. This library is based on promises that simplify sending asynchronous HTTP requests to REST endpoints. We will send a GET request to the JSONPlaceholder Posts API endpoint.
Unlike the Fetch API and XMLHttpRequest , Axios is not built-in. This means you need to install Axios in your JavaScript project.
To install a dependency into your JavaScript project, you will first initialize a new npm project by running the following command in your terminal:
And now, you can install Axios in your project by running the following command:
Once Axios is successfully installed, you can send your POST request. This is quite similar to the Fetch API request.
You will pass the API endpoint/URL to the post() method, which will return a promise. You can then handle the promise with the .then() and .catch() methods.
Note: Axios will automatically serialize the object to JSON and set the Content-Type header to ‘application/json’ for you.
This will return the new data sent to the server.
How to Send a POST Request with jQuery
Making an HTTP request in jQuery is similar to the Fetch API and Axios, but jQuery is not in-built. So you will first have to install or use its CDN in your project:
With jQuery, you can access the POST method $.post() , which takes in three parameters: the API endpoint/URL, the data to be sent to the server, and a callback function that runs when the request is successful.
Note: You can access the request’s data and status in the callback function.
Wrapping Up
In this article, you have learned how to send an HTTP POST request in JavaScript. You might now begin to think — which method should I use?
You can choose between the Fetch API and Axios if it’s a new project. Also, if you want to consume basic APIs for a small project, Axios is optional because it demands installing a library.
Have fun coding!
You can access over 150 of my articles by visiting my website. You can also use the search field to see if I’ve written a specific article.
How to Send GET and POST Requests with JavaScript Fetch API
![]()
It’s a common task for JavaScript developers to send GET and POST requests to retrieve or submit data. There are libraries like Axios that help you do that with beautiful syntax. However, you can achieve the same result with a very similar syntax with Fetch API, which is supported in all modern browsers.
Using the Fetch API, you don’t have to install an external library and thus, reduce the built file size. And you can still have a beautiful syntax with little code. Let’s do that!
Sending Requests with Fetch API
To send a GET request with Fetch API, use the following code:
To send a POST request, use the following code:
You can see the main difference between GET and POST requests is how the parameters are passed to the fetch call. In most cases, developers expect to pass an object of parameters and send requests in a beautiful syntax like this:
To do that, we need some code to transform the original code with fetch to the new syntax.
Creating get and post Functions
Because the codes that send requests are similar between GET and POST, we’ll create a common function request to make a request first. And then use it to create get and post functions like this:
Now it’s time to build the request function.
Note that for each function, we have a different way to construct parameters: they’re in the URL for GET, and in the body for POST. Thanks to URLSearchParams we can transform an object to a query string for the GET request.
Here is the first version:
The above code returns a promise, and you can use it in your app like this:
You can see it in action on CodeSandbox.
Caching Requests
One problem developers usually need is caching requests, to avoid sending the same request multiple times.
To implement caching, we can create an object to store the data and use it to return the data earlier:
WordPress REST API
As a WordPress developer, I usually work with the WordPress REST API. While the code above works fine in a general JavaScript app, it needs some changes to work in WordPress.
To send a request to the WordPress API, you need to authenticate the request. Also, the URL for REST requests must contain the WordPress base URL. Here is the updated code:
To send restBase and nonce to JavaScript, we need to use the wp_localize_script function as follows in your plugin or theme PHP file:
After that, you can make requests like this:
Conclusion
This post shows you how to make basic GET, POST requests in JavaScript with the Fetch API. It also shows you how to make requests for the WordPress REST API. With little code, we can have a beautiful syntax like in other libraries. You can use this method in your general JavaScript app or in a WordPress plugin.
I also wrote an article about modernizing JS code (improving and modernizing a large JavaScript codebase). So if you’re interested, you can read it to have a better code.
Fetch
JavaScript может отправлять сетевые запросы на сервер и подгружать новую информацию по мере необходимости.
Например, мы можем использовать сетевой запрос, чтобы:
- Отправить заказ,
- Загрузить информацию о пользователе,
- Запросить последние обновления с сервера,
- …и т.п.
Для сетевых запросов из JavaScript есть широко известный термин «AJAX» (аббревиатура от Asynchronous JavaScript And XML). XML мы использовать не обязаны, просто термин старый, поэтому в нём есть это слово. Возможно, вы его уже где-то слышали.
Есть несколько способов делать сетевые запросы и получать информацию с сервера.
Метод fetch() — современный и очень мощный, поэтому начнём с него. Он не поддерживается старыми (можно использовать полифил), но поддерживается всеми современными браузерами.
- url – URL для отправки запроса.
- options – дополнительные параметры: метод, заголовки и так далее.
Без options это простой GET-запрос, скачивающий содержимое по адресу url .
Браузер сразу же начинает запрос и возвращает промис, который внешний код использует для получения результата.
Процесс получения ответа обычно происходит в два этапа.
Во-первых, promise выполняется с объектом встроенного класса Response в качестве результата, как только сервер пришлёт заголовки ответа.
На этом этапе мы можем проверить статус HTTP-запроса и определить, выполнился ли он успешно, а также посмотреть заголовки, но пока без тела ответа.
Промис завершается с ошибкой, если fetch не смог выполнить HTTP-запрос, например при ошибке сети или если нет такого сайта. HTTP-статусы 404 и 500 не являются ошибкой.
Мы можем увидеть HTTP-статус в свойствах ответа:
- status – код статуса HTTP-запроса, например 200.
- ok – логическое значение: будет true , если код HTTP-статуса в диапазоне 200-299.
Во-вторых, для получения тела ответа нам нужно использовать дополнительный вызов метода.
Response предоставляет несколько методов, основанных на промисах, для доступа к телу ответа в различных форматах:
- response.text() – читает ответ и возвращает как обычный текст,
- response.json() – декодирует ответ в формате JSON,
- response.formData() – возвращает ответ как объект FormData (разберём его в следующей главе),
- response.blob() – возвращает объект как Blob (бинарные данные с типом),
- response.arrayBuffer() – возвращает ответ как ArrayBuffer (низкоуровневое представление бинарных данных),
- помимо этого, response.body – это объект ReadableStream, с помощью которого можно считывать тело запроса по частям. Мы рассмотрим и такой пример несколько позже.
Например, получим JSON-объект с последними коммитами из репозитория на GitHub:
Отправка форм при помощи JavaScript
HTML формы могут декларативно отправлять HTTP (en-US) -запросы. Но формы также могут подготовить HTTP-запросы для отправки с помощью JavaScript, например при помощи XMLHttpRequest . В этой статье исследуются подобные подходы.
Формы не всегда формы
В современных веб-приложениях, одностраничных приложениях и приложениях на основе фреймворков, обычно HTML-формы (en-US) используются для отправки данных без загрузки нового документа при получении данных ответа. В начале поговорим о том почему это требует другого подхода.
Получение контроля над глобальным интерфейсом
Отправка стандартной HTML формы, как описывалось в предыдущей статье, загружает URL-адрес, по которому были отправлены данные, это означает, что окно браузера перемещается с полной загрузкой страницы. Если избегать полную перезагрузку страницы, можно обеспечить более плавную работу, за счёт предотвращения задержек в сети и возможных визуальных проблем (например, мерцания).
Многие современные пользовательские интерфейсы используют HTML формы только для сбора пользовательского ввода, а не для для отправки данных. Когда пользователь пытается отправить свои данные, приложение берёт контроль и асинхронно передаёт данные в фоновом режиме, обновляя только ту часть всего интерфейса пользователя, которой требуется обновление.
Асинхронная отправка произвольных данных обычно называется AJAX, что означает «Asynchronous JavaScript And XML» (Асинхронный JavaScript и XML).
Чем он отличается?
Объект XMLHttpRequest (XHR) DOM может создавать HTTP-запросы, отправлять их, и получать их результат. Исторически, XMLHttpRequest был разработан для получения и отправки XML (en-US) в качестве формата обмена, который со временем был заменён на JSON (en-US) . Но ни XML, ни JSON не вписываются в кодировку запроса данных формы. Данные формы ( application/x-www-form-urlencoded ) состоят из списка пар ключ/значение в кодировке URL. Для передачи бинарных данных, HTTP-запрос преобразуется в multipart/form-data .
Примечание: Сейчас Fetch API часто используется вместо XHR — это современная, обновлённая версия XHR, которая работает в похожем стиле, но имеет несколько преимуществ. Большая часть XHR-кода, которую вы увидите в этой статье можно заменить на Fetch.
Если вы управляете фронтендом (кодом, который выполняется в браузере) и бэкендом (кодом, который выполняется на стороне сервера), вы можете отправлять JSON/XML и обрабатывать их как хотите.
Но если вы хотите использовать сторонний сервис, то вам необходимо отправлять данные в формате, который требуется сервису.
Так как нам следует отправлять подобные данные? Ниже описаны различные необходимые вам техники.
Отправка данных формы
Есть три способа отправки данных формы:
- Создание XMLHttpRequest вручную.
- Использование самостоятельного FormData объекта.
- Использование FormData связанного с <form> элементом.
Давайте рассмотрим их подробнее:
Создание XMLHttpRequest вручную
XMLHttpRequest это самый безопасный и надёжный способ создавать HTTP-запросы. Для отправки данных формы с помощью XMLHttpRequest , подготовьте данные с помощью URL-кодирования, и соблюдайте специфику запросов данных формы.
Посмотрите на пример:
И на JavaScript:
Примечание: This use of XMLHttpRequest is subject to the same-origin policy (en-US) if you want to send data to a third party web site. For cross-origin requests, you’ll need CORS and HTTP access control (en-US) .
Using XMLHttpRequest and the FormData object
Building an HTTP request by hand can be overwhelming. Fortunately, the XMLHttpRequest specification provides a newer, simpler way to handle form data requests with the FormData (en-US) object.
The FormData (en-US) object can be used to build form data for transmission, or to get the data within a form element to manage how it’s sent. Note that FormData (en-US) objects are «write only», which means you can change them, but not retrieve their contents.
Using this object is detailed in Using FormData Objects (en-US) , but here are two examples:
Using a standalone FormData object
You should be familiar with that HTML sample. Now for the JavaScript:
Here’s the live result:
Using FormData bound to a form element
You can also bind a FormData object to an <form> element. This creates a FormData object that represents the data contained in the form.
The HTML is typical:
But JavaScript takes over the form:
Here’s the live result:
You can even get more involved with the process by using the form’s elements property to get a list of all of the data elements in the form and manually manage them one at a time. To learn more about that, see the example in Accessing the element list’s contents в HTMLFormElement: elements property.
Dealing with binary data
If you use a FormData (en-US) object with a form that includes <input type=»file»> widgets, the data will be processed automatically. But to send binary data by hand, there’s extra work to do.
There are many sources for binary data, including FileReader , Canvas , and WebRTC (en-US) . Unfortunately, some legacy browsers can’t access binary data or require complicated workarounds. To learn more about the FileReader API, see Using files from web applications.
The least complicated way of sending binary data is by using FormData (en-US)‘s append() method, demonstrated above. If you have to do it by hand, it’s trickier.
In the following example, we use the FileReader API to access binary data and then build the multi-part form data request by hand:
As you see, the HTML is a standard <form> . There’s nothing magical going on. The «magic» is in the JavaScript:
Here’s the live result:
Conclusion
Depending on the browser and the type of data you are dealing with, sending form data through JavaScript can be easy or difficult. The FormData (en-US) object is generally the answer, and you can use a polyfill for it on legacy browsers.