為什麼在使用 axios.post 時我的頁面上有一個 OBJECT PROMISE (Why i have a OBJECT PROMISE on my page when using axios.post)


問題描述

為什麼在使用 axios.post 時我的頁面上有一個 OBJECT PROMISE (Why i have a OBJECT PROMISE on my page when using axios.post)

我嘗試將 axios 後查詢的結果放入 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] 我必須做些什麼來解決它?


參考解法

方法 1:

EDIT: here is a hosted codesandbox of an axios post working example: https://codesandbox.io/s/axios‑post‑example‑jg4yc?file=/src/App.vue

Following by the actual snippet

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;
},

Depending of what your API is doing, this kind of code should work fine.
I've also written an example of how a basic post to JSONplaceholder work in testJsonPlaceholder method (even if it's using fetch, it's pretty much the same thing, just remove the json() part).

<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>

I've also changed the kind of string interpolation with a stringify (nvm, axios does it by itself apparently: https://github.com/axios/axios#request‑config), doing the same stuff but easier to read.
If you don't want it, at least use Template Litterals (es6) to have something easy to interpolate like

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

Also, inspecting your network tab can help finding out where the issue is coming from !

(by Александр Пахомовkissu)

參考文件

  1. Why i have a OBJECT PROMISE on my page when using axios.post (CC BY‑SA 2.5/3.0/4.0)

#Axios #Vue.js #Promise #nuxt.js






相關問題

如何從 Contentful 中獲取單個條目並按字段值查詢? (How to fetch a single entry from Contentful and query by field value?)

VUE 中的 Axios 承諾失敗,無法讀取未定義的屬性“toUpperCase” (Axios promise in VUE failed with Cannot read property 'toUpperCase' of undefined)

Symfony 4 - 使用 Axios 提交表單? (Symfony 4 - Submit form with Axios?)

Laravel:帶有axios的表單不保存 (Laravel: form with axios not saving)

使用 axios 將用戶圖像上傳到strapi (uploading user image to strapi using axios)

我的 module.exports 返回為 [object Object] (My module.exports return as [object Object])

即使驗證要求無效,數據仍在發送,解決此問題的最佳方法是什麼? (Data is sending even if validation requirements are not valid, whats the best way to approach this?)

如何等到使用 Axios 上傳文件 (How to wait until file is uploaded using Axios)

axios 請求錯誤:使用 Heroku 的 ECONNREFUSED (axios request Error: ECONNREFUSED with Heroku)

為什麼我的 axios 調用即使在解決之後仍返回 undefined? (Why does my axios call return undefined even after then is resolved?)

為什麼在使用 axios.post 時我的頁面上有一個 OBJECT PROMISE (Why i have a OBJECT PROMISE on my page when using axios.post)

如何在使用反應測試庫單擊父組件上的按鈕後測試子組件呈現文本? (How to test the child component render text after the button on the parent component click with react testing library?)







留言討論