'Call a service api with Nuxt.js
I am using nuxt.js and I´d like to create a folder to put all my services api.
So, I create a services folder called services and I put into it my first service api:
// ClientesService.js in services folder
export default ($axios) => ({
list() {
return $axios.get('clientes')
},
})
Now, in my component, I call the service, but I get an error
TypeError: _services_ClientesService__WEBPACK_IMPORTED_MODULE_12__.default.list is not a function
at _callee2$ (medicos.vue?9853:155:1)
at tryCatch (runtime.js?96cf:63:1)
at Generator.invoke [as _invoke] (runtime.js?96cf:294:1)
at Generator.eval [as next] (runtime.js?96cf:119:1)
at asyncGeneratorStep (asyncToGenerator.js?1da1:3:1)
at _next (asyncToGenerator.js?1da1:25:1)
at eval (asyncToGenerator.js?1da1:32:1)
at new Promise (<anonymous>)
at eval (asyncToGenerator.js?1da1:21:1)
at VueComponent.getEspecialidades (medicos.vue?9853:155:1)
// My component ....
<script>
import ClientesService from '@/services/ClientesService'
export default {
name: 'Medicos',
data: () => ({
loading:false,
especialidades:[]
}),
async mounted() {
await this.getEspecialidades()
},
methods: {
async getEspecialidades() {
this.loading = true
try {
const resp = await ClientesService.list()
this.especialidades = resp.data
} catch (error) {
console.log(error)
} finally {
this.loading = false
}
},
},
}
</script>
Solution 1:[1]
I'd recommend create an ApiService that is just an axios instance (where you can define base api url, default headers, interceptors, etc) and use it in all other services. The code should look something like
import axios from 'axios';
const ApiService = new axios.create({
timeout: 30000,
baseURL: 'YOUR_API_URL',
headers: {
buildApplicationVersion: '1.0',
},
});
export default ApiService;
import ApiService from '@/Services/ApiService';
const list = () => {
return ApiService.get('clientes')
}
const CustomerService = {
list
}
export default CustomerService;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shaban Ramadani |
