Sending JSON to server using AJAX in JavaScript

You can send data to a server in the form of JSON. This is done in the following way:

button.addEventListener('click', function() { let promise = fetch('/handler/', { method: 'post', body: JSON.stringify([1, 2, 3, 4, 5]), headers: { 'Content-Type': 'application/json', }, }); });

On the server, the request body will be in body:

export default { '/handler/': function({ body }) { console.log(body); } }

Let's unpack the JSON received by the server:

export default { '/handler/': function({ body }) { console.log(JSON.parse(body)); } }

Send an array of data to a server. Let the server find the sum of this array elements and send back.

enru