Basic GET Request
fetch('/api/data')
.then(response => response.json()) // Convert response to JSON
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
fetch()
returns a Promise
that resolves to a Response
object.
- You must call
.json()
, .text()
, etc., to extract the actual data.
GET Request with Headers
fetch('/api/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_TOKEN'
}
})
.then(response => response.json())
.then(data => console.log(data));
- Custom headers like
Authorization
are useful for authentication.
- Always set
Content-Type
when sending JSON data.
POST Request with JSON Body
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));
- Use
JSON.stringify()
to send JSON data.
- The server must handle
Content-Type: application/json
.
PUT Request (Updating Data)
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));
PUT
is typically used to replace an existing resource.
PATCH Request (Partial Update)
fetch('/api/users/1', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ age: 35 }) // Only update `age`
})
.then(response => response.json())
.then(data => console.log(data));
PATCH
modifies part of the resource instead of replacing it.
DELETE Request
fetch('/api/users/1', { method: 'DELETE' })
.then(response => response.json())
.then(data => console.log('Deleted:', data));