How to Send and Receive JSON Data to and from the Server


JavaScript can send network requests to the server and load JSON. JS does this using something called AJAX. AJAX stands for Asynchronous JavaScript and XML. JS has an API, fetch, to GET(receive) and POST(send) information to the server.

You can use fetch to GET JSON data in the following way −

Example

const URL = 'https://jsonplaceholder.typicode.com/todos/1'
// Send a GET request without any data to the server
fetch(URL, {method: "GET"})
// Get the JSON data from the raw response
   .then(res => res.json())
// Print the result
   .then(console.log)

Output

This will give the output −

{
   "userId": 1,
   "id": 1,
   "title": "delectus aut autem",
   "completed": false
}

You can also POST data to the server using fetch. For example, to create a new todo on the above server, you can post your own data −

Example

const URL = 'https://jsonplaceholder.typicode.com/todos'
const data = {
   "userId": 1,
   "title": "delectus aut autem",
   "completed": false
};
// Send a post request
fetch(URL, {
   method: "POST",
   body: JSON.stringify(data),
   headers: {
      "Content-type": "application/json; charset=UTF-8"
   }
})

This will create a todo on the placeholder API.

Updated on: 27-Nov-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements