yoyojs
yoyojs

Reputation: 1773

adding headers to nuxt for making api rest call with axios

Inside my nuxt application i need to make call to an external api like this (file.vue) :

 <template>
  <div class="container">
    <h1>{{ post.title }}</h1>
    <pre>{{ post.body }}</pre>
    <p><nuxt-link to="/posts">Back to the list</nuxt-link></p>
  </div>
</template>

<script>
export default {
  async asyncData({ app }) {
    let { data } = await app.$axios.$get(`http://my.api.adress:8001/competition/sport/4?_format=json&limit=20&offset=0`)
    return { post: data }
  },
  head() {
    return {
      title: this.post.title
    }
  }
}
</script>

To make this call works i need to pass tree arguments to my headers. Anyone has an idea on how to do that to make it work for all api call in nuxt ?

Upvotes: 2

Views: 9809

Answers (1)

Schwesi
Schwesi

Reputation: 4904

You can set headers using the axios module for nuxt (which you already do).

Taken from their documentation:

setHeader(name, value, scopes='common')
name: Name of the header
value: Value of the header
scopes: Send only on specific type of requests.

Examples:

// Adds header: `Authorization: 123` to all requests
this.$axios.setHeader('Authorization', '123')

// Overrides `Authorization` header with new value
this.$axios.setHeader('Authorization', '456')

// Adds header: `Content-Type: application/x-www-form-urlencoded` to only 
// post requests
    this.$axios.setHeader('Content-Type', 'application/x-www-form-urlencoded', [
      'post'
    ])

// Removes default Content-Type header from `post` scope
this.$axios.setHeader('Content-Type', false, ['post'])


Please refer to the documentation for more information: https://github.com/nuxt-community/axios-module#setheadername-value-scopescommon

Upvotes: 3

Related Questions