Skip to content

Instantly share code, notes, and snippets.

@qant
Forked from Remzi1993/fetchExamples.js
Created January 7, 2020 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qant/d82ea379c5bb1b78feac63543bad088e to your computer and use it in GitHub Desktop.
Save qant/d82ea379c5bb1b78feac63543bad088e to your computer and use it in GitHub Desktop.
Examples of using native fetch
// 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