Categories
JavaScript Answers

How to send a JSON to server and retrieving a JSON in return with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *