The .json() method in JavaScript is used to take the data returned from a web request and convert it into a JavaScript object. This method reads the response body and automatically parses it as JSON.
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { console.log(data); // This will print the JSON data as a JavaScript object });
An HTTP GET request is used to retrieve data from a web server. In this example, the .json() method is used on the response to get the data in a format that JavaScript can work with.
fetch('https://api.example.com/data') .then(response => { if (response.ok) { return response.json(); } throw new Error('Request failed!'); }) .then(data => { console.log(data); // Prints the data retrieved from the server }) .catch(error => { console.error('Error:', error.message); // Prints any error that occurs during the request });
The fetch() function in JavaScript is used to make web requests. It sends a request to a server and returns a promise. If the request is successful, the promise resolves to a response object. If there is a network error, the promise is rejected with an error message.
fetch('https://api.example.com/submit', { method: 'POST', body: JSON.stringify({id: "200"}) }) .then(response => { if(response.ok){ return response.json(); } throw new Error('Request failed!'); }) .then(data => { console.log(data); // Prints the response data }) .catch(error => { console.error('Error:', error.message); // Prints any error that occurs during the request });
You can customize your web requests by adding options to the fetch() function, like including query parameters in the URL or using different HTTP methods (like GET or POST). This example shows how to use the async...await syntax to handle requests more smoothly.
const getSuggestions = async () => { const searchTerm = inputField.value; const endpoint = `${url}${queryParams}${searchTerm}`; try { const response = await fetch(endpoint, {cache: 'no-cache'}); if(response.ok){ const data = await response.json(); console.log(data); // Prints the response data } } catch(error) { console.error('Error:', error.message); // Prints any error that occurs during the request } };
An HTTP POST request is used to send data to a server, often to create or update resources. The fetch() function is used with the POST method to send this data.
fetch('https://api.example.com/submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({name: 'John', age: 30}) }) .then(response => response.json()) .then(data => { console.log('Success:', data); // Prints the response from the server }) .catch(error => { console.error('Error:', error.message); // Prints any error that occurs during the request });
The async...await syntax allows you to write cleaner and more readable code when making web requests. Instead of chaining .then() methods, you can use await to wait for a promise to resolve and then handle the response.
const fetchData = async () => { try { const response = await fetch('https://api.example.com/data'); if (response.ok) { const data = await response.json(); console.log(data); // Prints the response data } } catch (error) { console.error('Error:', error.message); // Prints any error that occurs during the request } };
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!