如何从axios获取响应标头?

问题描述 投票:0回答:1

我正在构建VueJS应用程序。我从wordpress rest api获取数据。我对javascript和VueJS不太熟悉。

  async getPosts({ state, commit, dispatch }) {
        if (state.posts.length) return
        try {
          let posts = await fetch(
            `${siteURL}/wp-json/wp/v2/posts?page=1&per_page=10&_embed=1`
          ).then(res => res.json())
           let total = res.headers['x-wp-total']
            console.log(total)
          posts = posts
            .filter(el => el.status === "publish")
            .map(({ id, slug, title, excerpt, date, tags, content, author, author_name  }) => ({
              id,
              slug,
              title,
              excerpt,
              date,
              tags,
              content,
              author,
              author_name
            }))



          commit("updatePosts", posts)

        } catch (err) {
          console.log(err)
        }

我的代码一直有效,直到我将它们添加到行中:

 let total = res.headers['x-wp-total']
            console.log(total)

我想从响应中获取标题以配置我的分页。这是我的错误消息:ReferenceError:未定义res在_callee $(VM770 app.js:5162)在tryCatch(VM768 commons.app.js:4486)在Generator.invoke上[作为_invoke](VM768 commons.app.js:4712)在Generator.prototype中。 [下一个](VM768 commons.app.js:4538)在asyncGeneratorStep(VM768 commons.app.js:31)在_next(VM768 commons.app.js:53)

感谢您的帮助。我认为我需要一些课程来理解一些JavaScript基本概念。因此,欢迎任何在线文档或课程。

vue.js ecmascript-6 axios try-catch ecmascript-5
1个回答
0
投票
  1. [res变量的作用域是作为then的回调提供的函数。

  2. 标题变量可以通过使用res.headers.get(string headerName)

  3. 访问
 async getPosts({ state, commit, dispatch }) {
        if (state.posts.length) return
          fetch(
            `${siteURL}/wp-json/wp/v2/posts?page=1&per_page=10&_embed=1`
          ).then((res) => {

           let total = res.headers.get('x-wp-total')
           console.log(total)
           posts = res.json()
            .filter(el => el.status === "publish")
            .map(({ id, slug, title, excerpt, date, tags, content, author, author_name  }) => ({
              id,
              slug,
              title,
              excerpt,
              date,
              tags,
              content,
              author,
              author_name
            }))
           commit("updatePosts", posts)
          }).catch ((err) => {
          console.log(err)
          })

© www.soinside.com 2019 - 2024. All rights reserved.