Sometimes, we want to send a JSON to server and retrieving a JSON in return with JavaScript
In this article, we’ll look at how to send a JSON to server and retrieving a JSON in return with JavaScript.
How to send a JSON to server and retrieving a JSON in return with JavaScript?
To send a JSON to server and retrieving a JSON in return with JavaScript, we use fetch.
For instance, we write
const dataToSend = JSON.stringify({
email: "hey@mail.com",
password: "101010",
});
const resp = await fetch(url, {
credentials: "same-origin",
mode: "same-origin",
method: "post",
headers: { "Content-Type": "application/json" },
body: dataToSend,
});
const dataReceived = await resp.json();
to call fetch to make a post request to the url in an async function.
We call fetch with the headers and body to send the request headers and body.
And then we get the JSON response body from the resp.json method.
Conclusion
To send a JSON to server and retrieving a JSON in return with JavaScript, we use fetch.