Skip to content

Instantly share code, notes, and snippets.

@rodrigooler
Created December 22, 2016 15:52
Show Gist options
  • Select an option

  • Save rodrigooler/e2589c6f592cc50350d0bd8f022c90eb to your computer and use it in GitHub Desktop.

Select an option

Save rodrigooler/e2589c6f592cc50350d0bd8f022c90eb to your computer and use it in GitHub Desktop.
api.js
const BASE_URL = 'http://localhost:8001/'
export async function callApi(endpoint, body, method, authenticated) {
const token = localStorage.getItem('id_token') || null
let config = {}
if (authenticated && token) {
config = {
method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({body})
}
} else {
config = {
method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"email": "[email protected]",
"password": "123"
})
}
}
return fetch(BASE_URL + endpoint, config).then((response) => {
console.log(config)
if (response.status >= 400) {
return Promise.reject(response)
}
return response.json()
}).then((result) => {
return Promise.resolve(result)
}).catch(err => console.log("Error: ", err))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment