[Vuejs]-Why i have a OBJECT PROMISE on my page when using axios.post

0👍

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 !

Leave a comment