Sending POST requests via AJAX in JavaScript

Let's now send a POST request to a server. To do this, the fetch function has a second parameter with settings. The method setting specifies the HTTP request method. We specify the POST method:

button.addEventListener('click', function() { let promise = fetch('/handler/', { method: 'post', }); });

Let's also define the data we want to send to the server. In POST requests, the data is passed in the HTTP request body. To do this, the data must be specified in the body setting. We specify them as a Query String, setting their type to the appropriate MIME:

button.addEventListener('click', function() { let promise = fetch('/handler/', { method: 'post', body: 'num1=1&num2=2', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }); });

Let's get this data on the server, do something with it and send it back:

export default { '/handler/': function({ post }) { return Number(post.num1) + Number(post.num2); } }

On a client, a div and a button are given. On clicking the button, send three numbers to a server using the POST method. Let the server find the sum of the passed numbers. Write the result in the div.

enru