Basic Usage
fetch(url)
→ Perform a GET request.
fetch(url, { method: 'POST', body: data })
→ Perform a request with a method and body.
- Returns a
Promise
that resolves to a Response
object.
- Must call
.json()
, .text()
, etc., to extract the actual data.
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Requests
GET Requests
- Basic GET request
- GET request with headers (e.g., authentication)
fetch('/api/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN'
}
})
.then(response => response.json())
.then(data => console.log(data));
POST Request (Send JSON)
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John Doe', age: 25 })
})
.then(response => response.json())
.then(data => console.log(data));
PUT Request (Full Update)
fetch('/api/users/1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Jane Doe', age: 30 })
})
.then(response => response.json())
.then(data => console.log(data));
PATCH Request (Partial Update)
fetch('/api/users/1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ age: 35 })
})
.then(response => response.json())
.then(data => console.log(data));
DELETE Request
fetch('/api/users/1', { method: 'DELETE' })
.then(response => response.json())
.then(data => console.log('Deleted:', data));
Request Object