Wednesday, 29 March 2023

Two ways to call Api in Nuxtjs

* Notice: this post apply for nuxtjs with typescipt

1. Method 1: using axios directly

- Install axios

yarn add @nuxtjs/axios

- Create file ./plugins/axios.ts

import axios from 'axios'

const api = axios.create({
baseURL: 'http://api.example.com',
headers: {
'Content-Type': 'application/json'
}
})

export default api

- Using to call Api

<template>
<div class="container">
<h1>Call Api</h1>
</div>
</template>

<script lang="ts">
import Vue from 'vue'
import api from '@/plugins/axios'

export default Vue.extend({
name: 'IndexPage',
created() {
this.asyncData();
},

methods: {
async asyncData() {
const response = await api.get('/products')
console.log(response)
}
}
})
</script>

2. Method 2: create plugin inject to context

- Install axios

yarn add @nuxtjs/axios

- Create file ./plugins/axios.ts

import { Plugin } from '@nuxt/types'
import axios from 'axios'

const axiosPlugin: Plugin = (context, inject) => {
// Set baseURL for Axios
axios.defaults.baseURL = process.env.API_URL || 'http://api.example.com'

// Inject axios instance to the context as $axios
inject('axios', axios)
}

export default axiosPlugin

- Edit file nuxt.config.js

plugins:
'~/plugins/axios.ts'
],

- Using to call Api

<template>
<div class="container">
<h1>Call API</h1>
</div>
</template>

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
name: 'IndexPage',
created() {
this.fetchData();
},

methods: {
async fetchData() {
try {
const response = await this.$axios.get('/products')
console.log(response.data)
} catch (error) {
console.error(error)
}
}
}
})
</script>

3. Change config when call API

- example change baseUrl

const response = await this.$axios.get('/members/products',{
  baseURL: 'https://localhost/api' 
})

Thank you


No comments:

Post a Comment

Golang Advanced Interview Q&A