Making Requests with JavaScript
🎯 Introduction
This article explains how browsers make network requests through the address bar, form submissions, and JavaScript using XMLHttpRequest and fetch. You will also learn to inspect request details, set headers, send JSON data, and handle results using modern asynchronous code. These are useful foundations for anyone new to frontend network requests.
🌐 How Browsers Make Requests
Browsers communicate with servers through HTTP requests. Understanding how a browser sends them is the foundation of understanding network communication.
What Happens When You Enter a URL
What happens when you enter a URL such as https://example.com in the address bar? The browser follows a complete request flow:
- It parses the URL into its scheme (HTTP/HTTPS), domain name, port (80 or 443 by default), and path.
- It queries DNS to resolve the domain name to an IP address.
- It establishes a TCP connection with the server (and performs a TLS handshake for HTTPS).
- It constructs an HTTP request message, using GET by default.
- It sends the request, and the server responds with data.
This process lets you access web resources. Think of requesting a pickup from a courier: you provide the address (domain name resolution), prepare the package (the request), and wait for the courier to deliver a reply (the server response).
Sending GET Requests from the Address Bar
Requests made through the address bar use GET by default.
The browser sends parameters in the URL directly to the server as a query string. For example:
https://example.com/search?q=javascript
The browser sends a request containing q=javascript, and the server returns the corresponding content.
Sending POST Requests with Forms
HTML forms are a common way for users to interact with servers. Set method="post" to submit a form using POST.
Example form:
<form action="/submit" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<button type="submit">Submit</button>
</form>
When you click the button, the browser serializes the form data (using application/x-www-form-urlencoded by default), places it in the request body, and sends it to the server.
POST requests are useful for submitting data, uploading files, and similar tasks.
🎨 Inspecting Requests in Browser Developer Tools (Network Panel)
You can inspect network request details using your browser's built-in developer tools.
Common shortcuts to open them are:
- Windows/Linux: F12 or Ctrl + Shift + I
- Mac: Cmd + Option + I
Switch to the Network panel to see the requests made by the current page. Select a request to inspect:
- Request headers (Headers)
- Request body (Payload)
- Response data (Response)
- Timing information (Timing)
This is a useful way to debug request problems and understand request details.
💻 Making Requests with JavaScript
Modern frontends use JavaScript requests to fetch data dynamically and render it on the page.
Basic XMLHttpRequest Usage
XMLHttpRequest (XHR) is an early browser API for making asynchronous requests.
Basic example - a GET request:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('Response data:', xhr.responseText);
} else {
console.error('Request failed. Status code:', xhr.status);
}
}
};
xhr.send();
Here is how the code works:
opensets the request method and URL- A callback monitors changes in request state
- Status code 200 indicates success, allowing you to read the response text
Sending GET / POST Requests with fetch()
fetch is a Promise-based request API available in modern browsers, with a more concise syntax.
GET request example:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not successful');
}
return response.json();
})
.then(data => {
console.log('Retrieved data:', data);
})
.catch(error => {
console.error('Request error:', error);
});
POST request example with JSON data:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
})
.then(response => response.json())
.then(data => console.log('Server response:', data))
.catch(error => console.error('Request failed:', error));
Setting Headers and Sending JSON Data
To send JSON, set the Content-Type header to application/json and convert the JavaScript object to a JSON string.
const data = { name: 'John Doe', age: 25 };
fetch('/api/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
Without the correct Content-Type, the server may not parse the request body correctly.
Writing Asynchronous Requests with async/await
async/await makes asynchronous code read more like synchronous code, with a clearer structure.
Example GET request:
async function fetchUser() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
if (!response.ok) {
throw new Error('Request failed. Status code: ' + response.status);
}
const user = await response.json();
console.log('User information:', user);
} catch (error) {
console.error('Request error:', error);
}
}
fetchUser();
Handling Errors and Exceptions (try/catch)
Network failures and server errors can occur during asynchronous requests. Use try/catch to catch exceptions.
Whether you use fetch or async/await, handle errors to prevent the page from failing or becoming unresponsive.
Tips
- Entering a URL in the address bar is the most direct example of a GET request.
- Form POST submissions support a limited set of data formats; JavaScript requests offer more flexibility.
- Beginners can start with fetch and async/await for concise, readable code.
- The Network panel in developer tools is a valuable tool for debugging requests.
❓ Questions and Answers
Q1: Which request method does the browser use by default when you enter a URL?
It sends a GET request to retrieve the resource.
Q2: How do you send a POST request with JSON data in JavaScript?
Use fetch with method: 'POST', add the 'Content-Type': 'application/json' header, and set body to the result of JSON.stringify() on your data.
Q3: Why wrap asynchronous request code in try/catch?
To catch network errors and request failures, prevent application crashes, and improve the user experience.
🧪 Exercises
Exercise 1: Write a function using fetch to POST an article (title and body) to https://jsonplaceholder.typicode.com/posts and log the data returned by the server.
async function createPost() {
// Write your code here
}
createPost();
Exercise 2: Use XMLHttpRequest to send a GET request to https://jsonplaceholder.typicode.com/users/1 and log the user information to the console.
function getUser() {
// Write your code here
}
getUser();
🎉 You now understand how browsers make requests, how to make asynchronous JavaScript requests, and how to use fetch! Keep building your frontend skills!
