chore: improved fetch operations feedbacks

This commit is contained in:
Roberto Tonino 2021-05-23 21:16:44 +02:00
parent f659afffd2
commit 513f6ca1c2
3 changed files with 29 additions and 10 deletions

File diff suppressed because one or more lines are too long

View File

@ -987,13 +987,14 @@ export default {
this.loggedInViaDeezer(res.arl)
}
},
loginWithCredentials() {
async loginWithCredentials() {
const fromLoginForm = getFormItem(this.$refs.loginWithCredentialsForm)
const { username } = fromLoginForm('username')
const { password } = fromLoginForm('password')
postToServer('loginWithCredentials', { username, password })
const response = await postToServer('loginWithCredentials', { username, password })
console.log({ response })
},
appLogin() {
socket.emit('applogin')

View File

@ -6,8 +6,15 @@ export function fetchData(key, data = {}, method = 'GET') {
})
return fetch(url.href, { method })
.then(response => response.json())
.catch(() => {})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok')
}
return response.json()
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error)
})
}
export function sendToServer(key, data) {
@ -17,17 +24,28 @@ export function sendToServer(key, data) {
url.searchParams.append(key, data[key])
})
fetch(url.href).catch(console.error)
fetch(url.href).catch(error => {
console.error('There has been a problem with your fetch operation:', error)
})
}
export const postToServer = (endpoint, data) => {
const url = new URL(`${window.location.origin}/api/${endpoint}`)
fetch(url, {
return fetch(url, {
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
}).catch(console.error)
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok')
}
return response.json()
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error)
})
}