首页 > 解决方案 > 为什么在使用 axios.post 时我的页面上有一个 OBJECT PROMISE

问题描述

我尝试将 axios post 查询的结果放到 dom 中:

 <v-btn fab color="#00C3EA" top right absolute class="white--text">
                            {{ getRating(tutor) }}
 </v-btn>

在我的方法上,我有这个:

async getRating(tutor) {
      let rating=0
      let lang = ''
      if (!this.language) {
         lang = this.$route.query.lang
      } else {
         lang = this.language
      }
      const rat = await this.$axios.$post('/tutors/getTutorRating.php', '{"tutor_id": '+tutor.id+', "lang": "'+lang+'"}').then((responce)=>{
        rating = responce.average_rating
      })
      console.log(rating)
      return rating
    },

在控制台日志中我有一个数字结果查询,在页面中我有 [object promise] 我必须做什么才能解决它?

标签: vue.jspromiseaxiosnuxt.js

解决方案


编辑:这是一个 axios 发布工作示例的托管代码框:https ://codesandbox.io/s/axios-post-example-jg4yc?file=/src/App.vue

接下来是实际的片段

async testJsonPlaceholder() {
  const json = await this.axios.post(
    "https://jsonplaceholder.typicode.com/posts",
    {
      title: "foo",
      body: "bar",
      userId: 1,
    },
    {
      headers: {
        "Content-type": "application/json; charset=UTF-8",
      },
    }
  );
  console.log("json", json.data);
  return json.data;
},

根据您的 API 正在做什么,这种代码应该可以正常工作。
我还写了一个示例,说明JSONplaceholder的基本帖子如何在testJsonPlaceholder方法中工作(即使它使用fetch,也几乎相同,只需删除json()部分)。

<script>
export default {
  methods: {
    async getRating(tutor) {
      let lang = ''
      if (!this.language) {
        lang = this.$route.query.lang
      } else {
        lang = this.language
      }
      const response = await this.$axios.$post(
        '/tutors/getTutorRating.php',
        JSON.stringify({ tutor_id: tutor.id, lang }),
      )

      const result = response.average_rating
      console.log("rating's value here", result)
      console.log(JSON.parse(JSON.stringify(result)))
      return result
    },

    // the one below is 100% working
    async testJsonPlaceholder() {
      const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: JSON.stringify({
          title: 'foo',
          body: 'bar',
          userId: 1,
        }),
        headers: {
          'Content-type': 'application/json; charset=UTF-8',
        },
      })

      const json = await response.json()
      console.log('json', json)
      return json
    },
  },
}
</script>

我还用 stringify 改变了字符串插值的类型(nvm,axios显然是自己做的:https ://github.com/axios/axios#request-config ),做同样的事情但更容易阅读。
如果你不想要它,至少使用Template Litterals (es6)有一些容易插值的东西,比如

`this is a simple string, but it's interpolated just here >> ${interpolatedHere} !` 

此外,检查您的网络选项卡可以帮助找出问题出在哪里!


推荐阅读