Explain Codes LogoExplain Codes Logo

Http GET request in JavaScript?

javascript
async-await
fetch-api
xmlhttprequest
Alex KataevbyAlex Kataev·Oct 3, 2024
TLDR

To quickly fetch data from the server using JavaScript's Fetch API:

fetch('https://api.example.com/data') .then(res => res.ok ? res.json() : Promise.reject(res)) .then(data => console.log(data)) .catch(err => console.error('Fetch error:', err));

This snippet fetches JSON data from a given URL, checks for successful responses, and logs the data; errors are distinctly marked.

Diving deep

Using good ol' XMLHttpRequest

For browser compatibility, leverage XMLHttpRequest:

var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.example.com/data', true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(JSON.parse(xhr.responseText)); // "Eureka! We hit a gold mine." } }; xhr.send();

This demonstrates how to make an asynchronous request, determine the readyState, and handle the corresponding response.

Handling errors the graceful way

Handle network errors and verify response statuses, regardless of fetch or XMLHttpRequest:

xhr.onerror = function() { console.error('Oh no, the XHR request surrendered!'); }; fetch('https://api.example.com/data').catch(err => console.error('Sorry, fetch just fetched an error :(', err));

These error handlers make sure your code is robust, providing user-friendly error messaging.

Synchronous requests: Exciting as watching paint dry

Both fetch and XMLHttpRequest can perform synchronous requests, but hold up! It's deprecated and a great way to freeze the main thread, creating the web equivalent of frozen pizza.

Asynchronicity and promises

Promises, promises

Older callback-based code can be refactored into promise-based code using fetch. You can use the async/await syntax for cleaner asynchronous code:

async function getData(url) { try { const response = await fetch(url); const data = await response.json(); console.log(data); // "Bingo! The suspense is finally over." } catch (error) { console.error('Oops, reality happened:', error); } } getData('https://api.example.com/data');

Polyfills: The browser's best friend

While fetch has good browser support, a polyfill such as GitHub's fetch polyfill adds compatibility for any straggler browsers.

Keeping it clean and tidy

A reusable class or function for HTTP requests declutters your codebase:

class HttpService { static async get(url) { const response = await fetch(url); return response.json(); // "Oh look, treasure!" } } HttpService.get('https://api.example.com/data').then(console.log).catch(console.error);

Different strokes for different folks

If you got jQuery, use jQuery

jQuery abstracts away complexities and lets you make a GET request like such:

$.get('https://api.example.com/data', function(data) { console.log(data); }).fail(function() { console.error('Oops, jQuery couldn’t get it.'); });

But remember, be aware of your project's needs regarding size and performance.

A wild environment appears

Ensure your chosen method is supported in niche environments like Mac OS X dashcode widgets. jQuery and fetch polyfills have your back here.

Fast but uninformative

For quick GET requests sans response handling, an img element with a dynamic src can do the trick:

var img = new Image(); img.src = 'http://api.pizzeria.com/track-order?orderId=12345'; // "Who knew pizza tracking could be so easy!"

Simple yet effective, similar to the joy in finding cash in old jeans. Don't knock it 'til you've tried it!