Fetch/XMLHttpRequest in TypeScript
This article explains Fetch/XMLHttpRequest in TypeScript.
You can learn about how to use the Fetch API and XMLHttpRequest, as well as their differences.
YouTube Video
Fetch/XMLHttpRequest in TypeScript
In TypeScript, HTTP requests are mainly conducted using two APIs: Fetch API and XMLHttpRequest. By using TypeScript, you can introduce type checking for requests and responses when performing asynchronous communication with these APIs, allowing you to write safer code. Below, we will introduce how to use each of them.
Fetch API
The Fetch API is a Promise-based API used to perform asynchronous communication (HTTP requests) simply. In TypeScript, you can make requests using the fetch method and process responses in a type-safe manner.
Basic Usage
Below is a basic example using a GET request.
1const url = 'https://jsonplaceholder.typicode.com/posts';
2
3fetch(url)
4 .then(response => {
5 if (!response.ok) {
6 throw new Error('Network response was not ok');
7 }
8 return response.json(); // Parse the response as JSON
9 })
10 .then(data => {
11 console.log(data);
12 })
13 .catch(error => {
14 console.error('Fetch error:', error);
15 });- This code sends a
GETrequest to the specified URL, parses the received response as JSON, and outputs it to the console.
Type-safe data handling in TypeScript
Since the response from the fetch method has an unclear type, you can leverage TypeScript's type checking by explicitly defining the response type.
1// Define the type for the response data
2interface Post {
3 userId: number;
4 id: number;
5 title: string;
6 body: string;
7}
8
9const url = 'https://jsonplaceholder.typicode.com/posts';
10
11fetch(url)
12 .then(response => response.json())
13 .then((data: Post[]) => {
14 data.forEach(post => {
15 console.log(`Title: ${post.title}`);
16 });
17 })
18 .catch(error => {
19 console.error('Error fetching data:', error);
20 });- This code applies the
Posttype to the data retrieved withfetch, processes the response in a type-safe manner, and outputs the title of each post to the console.
Example of a POST request
When sending data to the server, use the POST method. To send JSON in the body, specify headers and body.
1const postData = {
2 title: 'foo',
3 body: 'bar',
4 userId: 1
5};
6
7fetch('https://jsonplaceholder.typicode.com/posts', {
8 method: 'POST',
9 headers: {
10 'Content-Type': 'application/json'
11 },
12 body: JSON.stringify(postData)
13 })
14 .then(response => response.json())
15 .then(data => {
16 console.log('Created post:', data);
17 })
18 .catch(error => {
19 console.error('Error posting data:', error);
20 });- This code sends data in JSON format to the server with a
POSTrequest, receives the response as JSON, and outputs it to the console.
Fetch using asynchronous functions (async/await)
By using async/await in TypeScript, you can write asynchronous processing more simply.
1// Define the type for the response data
2interface Post {
3 userId: number;
4 id: number;
5 title: string;
6 body: string;
7}
8
9async function fetchPosts() {
10 try {
11 const response = await fetch('https://jsonplaceholder.typicode.com/posts');
12 if (!response.ok) {
13 throw new Error('Network response was not ok');
14 }
15 const data: Post[] = await response.json();
16 console.log(data);
17 } catch (error) {
18 console.error('Fetch error:', error);
19 }
20}
21
22fetchPosts();- This code asynchronously fetches post data using the
async/awaitsyntax, processes the response as aPost[]type, and outputs it to the console.
XMLHttpRequest
XMLHttpRequest is an older API and is somewhat more complex compared to the Fetch API, but it may be used when browser compatibility or more advanced control is necessary.
Basic usage of XMLHttpRequest
Below is an example using a GET request.
1const xhr = new XMLHttpRequest();
2xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true);
3
4xhr.onreadystatechange = function () {
5 if (xhr.readyState === 4 && xhr.status === 200) {
6 const data = JSON.parse(xhr.responseText);
7 console.log(data);
8 }
9};
10
11xhr.send();- This code sends a
GETrequest to the specified URL usingXMLHttpRequest, parses the response as JSON, and outputs it to the console.
Example of a POST request
When sending data to the server, specify POST in the open method and send data with send.
1const xhr = new XMLHttpRequest();
2xhr.open('POST', 'https://jsonplaceholder.typicode.com/posts', true);
3xhr.setRequestHeader('Content-Type', 'application/json');
4
5const postData = JSON.stringify({
6 title: 'foo',
7 body: 'bar',
8 userId: 1
9});
10
11xhr.onreadystatechange = function () {
12 if (xhr.readyState === 4 && xhr.status === 201) {
13 console.log('Created post:', xhr.responseText);
14 }
15};
16
17xhr.send(postData);- This code sends data in JSON format to the server with a
POSTrequest usingXMLHttpRequest, and outputs the response containing the created data to the console.
Error handling with XMLHttpRequest
You can handle request errors by using the onerror event.
1const xhr = new XMLHttpRequest();
2xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true);
3
4xhr.onerror = function () {
5 console.error('Request failed');
6};
7
8xhr.onload = function () {
9 if (xhr.status === 200) {
10 console.log('Response:', xhr.responseText);
11 } else {
12 console.error('Error:', xhr.status);
13 }
14};
15
16xhr.send();- This code executes a
GETrequest withXMLHttpRequest, handles request errors withonerror, and appropriately logs the response on both success and failure.
Comparison of Fetch API and XMLHttpRequest
| Feature | Fetch API | XMLHttpRequest |
|---|---|---|
| Modern API | ○ | × |
| Promise Support | ○ | × |
| Readability | High (works well with async/await) |
Low (many callbacks) |
| Browser Compatibility | Not supported in some older browsers | Supported by all major browsers |
| Progress Tracking | △ (possible with ReadableStream) |
○ (onprogress event available) |
| Error Handling | Errors are caught in the Promise chain | Need to use onerror |
Summary
In TypeScript, you can write asynchronous requests concisely and type-safe code by using the Fetch API. On the other hand, XMLHttpRequest is an older API but may still be used in certain situations. Generally, it is recommended to use the simple and modern Fetch API, but if browser compatibility or progress tracking is needed, XMLHttpRequest can also be considered.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.