Created
March 20, 2019 20:01
-
-
Save danielschmitz/90e146e664a5ec3a7d4d6edf4a75677e to your computer and use it in GitHub Desktop.
AXIOS e VUE, como fazer
This file contains hidden or 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
import http from './http' | |
const associadoService = { | |
getAll: page => http.get(`/associados?page=${page}`), | |
getById: id => http.get(`/associados/${id}`) | |
} | |
export default associadoService |
This file contains hidden or 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
<template> | |
... | |
</template> | |
<script> | |
import associadoService from '@/services/associado' | |
export default { | |
data: () { | |
return { | |
associados: [] | |
} | |
}, | |
async mounted() { | |
this.associados = await associadoService.getAll(); | |
} | |
} | |
</script> |
This file contains hidden or 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
import axios from 'axios' | |
import store from '../store' | |
import router from '../router' | |
/** | |
* Classe responsável em realizar os acessos do frontend ao backend | |
* A URL de acesso está no arquivo .env | |
* | |
* Para fazer uma chamada GET, use http.get() | |
* Para fazer uma chamada POST, use http.post() | |
* | |
* Não é preciso repassar a URL completa na chamada get ou post. | |
* Basta repassar a parte final como por exemplo '/api/usuarios/getAll' | |
*/ | |
const http = axios.create({ | |
baseURL: process.env.VUE_APP_ROOT_API, | |
timeout: 10000, | |
headers: { 'Content-Type': 'application/json' } | |
}) | |
/** | |
* Interceptador para todas as requisições do frontend ao backend | |
* Se houver um token, envia o token no cabeçalho da requisição http | |
*/ | |
http.interceptors.request.use( | |
config => { | |
const token = store.token | |
if (token !== '') config.headers.Authorization = `Bearer ${token}` | |
return config | |
}, | |
error => Promise.reject(error) | |
) | |
/** | |
* Interceptador para todas as respostas do backend ao frontend | |
* Se o servidor redirecionar com 401 (sem autorização), deve ir | |
* para a tela de login. | |
*/ | |
http.interceptors.response.use( | |
response => { | |
const refreshToken = response.headers['refresh'] | |
if (refreshToken !== undefined) | |
store.token = refreshToken | |
return response | |
}, | |
error => { | |
if (error.response !== undefined) { | |
if (error.response.status === 401) { | |
store.logout() | |
router.push('/') | |
} | |
// TODO Adicionar mais alguns status de erro, como o 404 e o 500 | |
} else { | |
// eslint-disable-next-line | |
console.log('Erro ao acessar o servidor: ' + error) | |
} | |
// Independente do erro, o Promise.reject garante a quem chamou | |
// o backend possa também tratá-lo (catch). | |
return Promise.reject(error) | |
} | |
) | |
export default http |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Valeu mano, seu exemplo ficou show!