Javascript fetch API is “used to provide an interface for accessing and manipulating parts of the protocol, such as requests and responses.”
Syntax
let promise = fetch(URL, [options])
Parameters
- URL: The URL to access.
- options: – Optional parameters: method, headers, etc. Without options, that is the simple GET request, downloading the contents of the url.
Return value
The fetch() method returns a Promise that resolves to a Response object.
JavaScript fetch() GET Request
To make a simple GET request with fetch, you must pass in the “URL endpoint as an argument”.
Syntax
fetch('url')
.then(response => response.json())
.then(data => console.log(data));
Example
Straightforwardly, all you do is call fetch with the URL you want; by default, the Fetch API uses the GET method, so a direct call would be like this.
fetch('https://api.github.com/users/KrunalLathiya')
.then(response => response.json())
.then(data => {
console.log(data) // Prints result from `response.json()` in getRequest
})
.catch(error => console.error(error))
Here, we get a response, and the response is a Stream object, and the response we get is not JSON but a simple object with a series of methods that we can use further to process the data way we want.
- clone() – This method implies that this method creates a response clone.
- json() – This method resolves the promise with JSON.
- redirect() – This method creates a new response but with a different URL.
- text() – In this case, it resolves with a string.
- arrayBuffer() – Here, we return a promise that resolves with an ArrayBuffer.
- blob() – This is one determined with a Blob.
- formData() returns a promise but determines with the FormData object.
Response Metadata
In the above example, we have seen the status of a Response object and how to parse a response as JSON. In addition, we can access other metadata like headers. So visit the following code.
fetch('users.json').then(function(response) {
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));
console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
});
Response Types
You can define the mode for a fetch request such that only specific requests will resolve. The modes you can set are as follows:
- A same-origin only succeeds for the requests for assets on the same origin, and all the other requests will reject.
- The CORS will allow asset requests on the exact origin and other origins, which return appropriate CORS headers.
- The cors-with-forced-preflight will always perform a preflight check before making an actual request.
- The no-cors is intended to make the requests to other origins that do not have the CORS headers and result in an opaque, but as stated, this isn’t possible in the window global scope.
If we want to define the mode, add the options object as a second parameter in the fetch request, and define a mode in that object.
fetch('https://facebook.com/cors-enabled/some.json', {mode: 'cors'})
.then(function(response) {
return response.text();
})
.then(function(text) {
console.log('Request successful', text);
})
.catch(function(error) {
log('Request failed', error)
});
Request Headers
fetch('https://api.github.com/users/KrunalLathiya', {
headers: new Headers({
'User-agent': 'Mozilla/4.0 Custom User Agent'
})
})
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(error => console.error(error))
JavaScript fetch() POST Request
To send a POST request using fetch(), you must specify the HTTP method name in the “method” parameter and the POST data in the “body” parameter. Additional HTTP headers can be specified in the “headers” parameter.
Syntax
fetch(url, {
method: 'POST', // Specify the method
headers: {
'Content-Type': 'application/json', // Set the content type in headers
},
body: JSON.stringify(data), // Convert the data to a string
})
.then(response => response.json()) // Parse the response as JSON
.then(data => console.log(data)) // Log the data
.catch(error => console.error('Error:', error));
Example
postRequest('https://appdividend.com/api/v1/users', {user: 'Krunal'})
.then(data => console.log(data)) // Result from the `response.json()` call
.catch(error => console.error(error))
function postRequest(url, data) {
return fetch(url, {
credentials: 'same-origin', // 'include', default: 'omit'
method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
body: JSON.stringify(data), // Coordinate the body type with 'Content-Type'
headers: new Headers({
'Content-Type': 'application/json'
}),
});
.then(response => response.json())
}
Here, we have created a postRequest function and passed the two parameters. The first parameter is the request, and the second is the data that must be stored on the server.
Conclusion
JavaScript Fetch API provides a fetch() method defined on a window object, which you can use to perform requests and send them to the server. This method returns a Promise that you can use to retrieve the response to the request.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
if interface API return customer status, for example:
res.status == 0
.then(/*handle something*/)
or
res.status == 1
.then(/*handle something*/)
or
res.status == 2
.then(/*handle something*/)
in Fetch, how to resolve?
Nice article Krunal. One question rather doubt, is is necessary to handle error scenario with catch block here or we can pass this ownership to calling method?
hi can you please post how to display the fetch response in a web browser