Sunday 5 August 2018

html - How to call a REST web service API from JavaScript?



I have an HTML page with a button on it. When I click on that button, I need to call a REST Web Service API. I tried searching online everywhere. No clue whatsoever. Can someone give me a lead/Headstart on this? Very much appreciated.


Answer



I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.




The API includes a lot more, but start with the fetch() method. It takes two arguments:




  1. A URL or an object representing the request.

  2. Optional init object containing the method, headers, body etc.



Simple GET:




const userAction = async () => {
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}


Recreating the previous top answer, a POST:



const userAction = async () => {

const response = await fetch('http://example.com/movies.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...