JavaScript enables interaction with servers through HTTP requests to fetch or send data. The most common modern approach uses the fetch() API, which returns promises for asynchronous handling.

Basic GET Request with fetch()
Use fetch() with a URL to retrieve data. It returns a promise resolving to a Response object.
📌 Deep Dive: Simple GET Request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Sending Data with POST Requests
To send data, specify method and body options. Usually, the body is serialized JSON.
📌 Deep Dive: POST Request Example
fetch('https://api.example.com/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice', age: 30 })
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.error('Error:', error));
Common HTTP Methods
| Method | Purpose |
|---|---|
| GET | Retrieve data from server |
| POST | Send new data to server |
| PUT | Update existing data |
| DELETE | Remove data |
💡 Handling Responses
Always check the response.ok property or status code before processing data to handle errors gracefully.
Using Async/Await for Cleaner Syntax
Async functions allow easier reading and error handling with try/catch.
📌 Deep Dive: Async/Await Fetch
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
getData();
⚠️ CORS Restrictions
Cross-Origin Resource Sharing policies can block requests to different domains unless the server allows it via headers.
Summary
fetch()is the modern way to make HTTP requests in JavaScript.- It returns promises that resolve to response objects; parse with
response.json()orresponse.text(). - Set HTTP method, headers, and body in options for POST, PUT, DELETE requests.
- Use
async/awaitfor more readable asynchronous code. - Always handle errors and check response status.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does fetch() return when making an HTTP request?
Question 2 of 2
Which HTTP method is typically used to send new data to a server?
Loading results...