【问题标题】:adding headers to nuxt for making api rest call with axios将标头添加到 nuxt 以使用 axios 进行 api rest 调用
【发布时间】:2018-01-24 09:31:03
【问题描述】:

在我的 nuxt 应用程序中,我需要像这样调用外部 api (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>

为了使这个调用有效,我需要将树参数传递给我的标题。任何人都知道如何做到这一点以使其适用于 nuxt 中的所有 api 调用?

【问题讨论】:

    标签: vuejs2 fetch axios nuxt.js


    【解决方案1】:

    您可以使用 axios module 为 nuxt 设置标题(您已经这样做了)。

    取自their documentation

    setHeader(name, value, scopes='common')
    name:标题的名称
    value:标头的值
    范围:仅针对特定类型的请求发送。

    示例:

    // 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'])
    


    更多信息请参考文档:https://github.com/nuxt-community/axios-module#setheadername-value-scopescommon

    【讨论】:

    • 在这种情况下this 指的是什么?我在文档中看不到它..
    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2020-04-27
    • 2022-01-11
    • 2017-12-27
    • 1970-01-01
    相关资源
    最近更新 更多