Last active
January 30, 2024 06:21
-
-
Save Remzi1993/229eec249de93be22a822ca15ed8e7cf to your computer and use it in GitHub Desktop.
Examples of using native fetch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Config / constants | |
const baseUrl = 'http://localhost:4000' || 'example.herokuapp.com' // or use an environment variable like this: process.env.URL || 'http://localhost:4000' | |
const JWT = 'Whatever-token' | |
/* | |
* Examples of using native fetch | |
* REST API - CRUD convention (Create/POST, Read/GET, Update/modify/PUT/PATCH, Delete/DELETE) | |
* | |
**/ | |
/* | |
* Explanation why to use "Bearer" in the Authorization header: | |
* - https://security.stackexchange.com/questions/108662/why-is-bearer-required-before-the-token-in-authorization-header-in-a-http-re | |
* - https://stackoverflow.com/questions/33265812/best-http-authorization-header-type-for-jwt | |
* | |
**/ | |
/* | |
* All endpoints are usually plural (REST API convention) | |
* - https://stackoverflow.com/questions/6845772/rest-uri-convention-singular-or-plural-name-of-resource-while-creating-it | |
* - https://gearheart.io/blog/restful-api-design-best-practices/ | |
* | |
**/ | |
// HTTP status codes: https://www.restapitutorial.com/lessons/httpmethods.html | |
// See list of status codes: https://httpstatuses.com | |
// Example POST request | |
fetch(`${baseUrl}/whatever-endpoint`, { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
'Authorization': `Bearer ${JWT}` | |
}, | |
body: JSON.stringify({ | |
sendSomething, | |
sendSomething2, | |
sendSomething3 | |
}) | |
}) | |
.then(response => Promise.all([response, response.json()])) | |
.then(([response, json]) => { | |
// console.log('response', response); | |
if (!response.ok || !response.status === 201) { // We should get a 201 (Created) status code if everything is fine/working | |
throw Error(`Respsonse status ${response.status} (${response.statusText}): ${json.message}`); | |
} | |
// console.log(json); | |
// Whatever you want to do next after the POST request - maybe dispatch something? | |
}) | |
.catch(exception => { | |
console.log(new Map([ | |
[TypeError, "There was a problem fetching the response."], | |
[SyntaxError, "There was a problem parsing the response."], | |
[Error, exception.message] | |
]).get(exception.constructor())); | |
}); | |
// Example GET request | |
fetch(`${baseUrl}/whatever-endpoint`, { | |
method: 'GET', | |
headers: { | |
'Content-Type': 'application/json', | |
'Authorization': `Bearer ${JWT}` // Not always needed with a GET request | |
} | |
}) | |
.then(response => Promise.all([response, response.json()])) | |
.then(([response, json]) => { | |
// console.log('response', response); | |
if (!response.ok) { // We should get a 200 (OK) status code if everything is fine/working | |
throw Error(`Respsonse status ${response.status} (${response.statusText}): ${json.message}`); | |
} | |
// console.log(json); | |
// Whatever you want to do next after fetching - maybe dispatch something? | |
}) | |
.catch(exception => { | |
console.log(new Map([ | |
[TypeError, "There was a problem fetching the response."], | |
[SyntaxError, "There was a problem parsing the response."], | |
[Error, exception.message] | |
]).get(exception.constructor())); | |
}); | |
// Example GET request with id | |
fetch(`${baseUrl}/whatever-endpoint/${encodeURIComponent(userId)}`, { | |
method: 'GET', | |
headers: { | |
'Content-Type': 'application/json', | |
'Authorization': `Bearer ${JWT}` // Not always needed with a GET request | |
} | |
}) | |
.then(response => Promise.all([response, response.json()])) | |
.then(([response, json]) => { | |
// console.log('response', response); | |
if (!response.ok) { // We should get a 200 (OK) status code if everything is fine/working | |
throw Error(`Respsonse status ${response.status} (${response.statusText}): ${json.message}`); | |
} | |
// console.log(json); | |
// Whatever you want to do next after fetching - maybe dispatch something? | |
}) | |
.catch(exception => { | |
console.log(new Map([ | |
[TypeError, "There was a problem fetching the response."], | |
[SyntaxError, "There was a problem parsing the response."], | |
[Error, exception.message] | |
]).get(exception.constructor())); | |
}); | |
// Example PUT resquest - with token and encodeURIComponent | |
fetch(`${baseUrl}/whatever-endpoint/${encodeURIComponent(userId)}`, { | |
method: 'PUT', | |
headers: { | |
'Content-Type': 'application/json', | |
'Authorization': `Bearer ${JWT}` | |
}, | |
body: JSON.stringify({ | |
sendSomething, | |
sendSomething2, | |
sendSomething3 | |
}) | |
}) | |
.then(response => Promise.all([response, response.json()])) | |
.then(([response, json]) => { | |
// console.log('response', response); | |
if (!response.ok || !response.status === 204) { // We should get a 200 (OK) or 204 (No Content) status code if everything is fine/working | |
throw Error(`Respsonse status ${response.status} (${response.statusText}): ${json.message}`); | |
} | |
// console.log(json); | |
// Whatever you want to do next after the PUT request - maybe dispatch something? | |
}) | |
.catch(exception => { | |
console.log(new Map([ | |
[TypeError, "There was a problem fetching the response."], | |
[SyntaxError, "There was a problem parsing the response."], | |
[Error, exception.message] | |
]).get(exception.constructor())); | |
}); | |
// Example PATCH resquest - with token and encodeURIComponent | |
fetch(`${baseUrl}/whatever-endpoint/${encodeURIComponent(userId)}`, { | |
method: 'PATCH', | |
headers: { | |
'Content-Type': 'application/json', | |
'Authorization': `Bearer ${JWT}` | |
}, | |
body: JSON.stringify({ | |
sendSomething, | |
sendSomething2, | |
sendSomething3 | |
}) | |
}) | |
.then(response => Promise.all([response, response.json()])) | |
.then(([response, json]) => { | |
// console.log('response', response); | |
if (!response.ok || !response.status === 204) { // We should get a 200 (OK) or 204 (No Content) status code if everything is fine/working | |
throw Error(`Respsonse status ${response.status} (${response.statusText}): ${json.message}`); | |
} | |
// console.log(json); | |
// Whatever you want to do next after the PATCH request - maybe dispatch something? | |
}) | |
.catch(exception => { | |
console.log(new Map([ | |
[TypeError, "There was a problem fetching the response."], | |
[SyntaxError, "There was a problem parsing the response."], | |
[Error, exception.message] | |
]).get(exception.constructor())); | |
}); | |
// Example DELETE resquest - with token and encodeURIComponent | |
fetch(`${baseUrl}/whatever-endpoint/${encodeURIComponent(userId)}`, { | |
method: 'DELETE', | |
headers: { | |
'Content-Type': 'application/json', | |
'Authorization': `Bearer ${JWT}` | |
}, | |
body: JSON.stringify({ | |
sendSomething, | |
sendSomething2, | |
sendSomething3 | |
}) | |
}) | |
.then(response => Promise.all([response, response.json()])) | |
.then(([response, json]) => { | |
// console.log('response', response); | |
if (!response.ok) { // We should get a 200 (OK) status code if everything is fine/working | |
throw Error(`Respsonse status ${response.status} (${response.statusText}): ${json.message}`); | |
} | |
// console.log(json); | |
// Whatever you want to do next after the DELETE request - maybe dispatch something? | |
}) | |
.catch(exception => { | |
console.log(new Map([ | |
[TypeError, "There was a problem fetching the response."], | |
[SyntaxError, "There was a problem parsing the response."], | |
[Error, exception.message] | |
]).get(exception.constructor())); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment