npm install @nuxtjs/axios
nuxt.config.js:
module.exports = {
modules: [
'@nuxtjs/axios',
]
}
API Server:
npm i -g json-server
To run the API server:
json-server --watch db.json
json-server --watch db.json --delay 2000
/nuxt.config.js:
...
/* ** Customize the progress-bar color */
loading: {
color: '#39b982'
},
...
<template>
<div
v-for="(event, index) in events"
:key="index"
>
{{ event }}
</div>
</template>
<script>
export default {
asyncData({ $axios, error }) {
return $axios
.get('http://localhost:3000/events')
.then(response => {
return {
events: response.data
}
})
.catch(e => {
error({
statusCode: 503,
message: 'Unable to fetch events at this time. Please try again.'
})
})
}
}
</script>
<template>
<div
v-for="(event, index) in events"
:key="index"
>
{{ event }}
</div>
</template>
<script>
export default {
async asyncData({ $axios, error }) {
try {
const { data } = await $axios.get('http://localhost:3000/events')
return {
events: data
}
} catch (e) {
error({
statusCode: 503,
message: 'Unable to fetch events at this time. Please try again.'
})
}
}
}
</script>