to extract data from a multitude of formats. But to parse data from JSON you need just one method — response.json().
2. GET JSON data
Let's fetch from the path /api/names a list of persons in JSON format:
asyncfunctionloadNames() {
constresponse = awaitfetch('/api/names');
constnames = awaitresponse.json();
console.log(names);
// logs [{ name: 'Joker'}, { name: 'Batman' }]
}
loadNames();
await fetch('/api/names') starts a GET request, and evaluates to the response object when the request is complete.
Then, from the server response, you can parse the JSON into a plain JavaScript object using await response.json() (note: response.json() returns a promise!).
By default fetch() performs a GET request. But you can always indicate the HTTP method explicitly:
// ...
constresponse = awaitfetch('/api/names', {
method:'GET'
});
// ...
2.1 Explicitly asking for JSON
Some API servers might work with multiple formats: JSON, XML, etc. That's why these servers might