Hippie
Hippie

Reputation: 25

Axios returns a string instead of JSON (vue.js)

I don't understand why but axios is returning a string instead of JSON. Can someone explain me why?

<template>
    <div class="app">
        <Header/>
                <h1>{{services}}</h1>
                <Services v-bind:services="services"></Services>
    </div>
</template>

<script>
    import Header from "./components/Header.vue";
    import Services from "@/components/Service";
    import axios from 'axios';

    export default {
        name: 'App',
        components: {
            Services,
            Header,
        },
        data() {
            return {
                services: [],
            }
        },
        created() {
            const instance = axios.create({
                baseURL: 'http://localhost:3000/api',
                timeout: 1000,
                headers: {'Authorization': 'Bearer ' + 'mysecretcode'}
            });
            instance.get('/service')
                .then(response => {
                    this.services = response.data;
                    console.log(response.data);
                })
                .catch(e => {
                    this.errors.push(e)
                })
        },
    }

</script>

<style>
</style>

I saw online that response.data is supposed to send back only the parsed json data but on my {{services}} I get this :

{ "status": 1, "message": "Operation success", "data": [ { "_id": "5edfdaf5586d4c75036bc853", "title": "Logo rapide", "description": "testing service desc", "createdAt": "2020-06-09T18:54:45.904Z" }, { "_id": "5edfdafd586d4c75036bc854", "title": "Logo rapide", "description": "testing service desc", "createdAt": "2020-06-09T18:54:53.054Z" }, { "_id": "5edfdc8bc07c7677915275c1", "title": "Logo rapide", "description": "testing service desc", "createdAt": "2020-06-09T19:01:31.945Z" }, { "_id": "5edfdc8cc07c7677915275c2", "title": "Logo rapide", "description": "testing service desc", "createdAt": "2020-06-09T19:01:32.621Z" } ] }

instead of the parsed data. Thank you :)

Upvotes: 2

Views: 6437

Answers (4)

Daniel
Daniel

Reputation: 8687

You can use interceptior to fix this bug

  const client = new Axios({});

  // Fix typeof data === 'string' in axios
  client.interceptors.response.use(
    function (response) {
      try {
        if (typeof response.data === 'string') {
          response.data = JSON.parse(response.data);
        }
      } catch {
        /* empty */
      }

      return response;
    },
    function (error) {
      return Promise.reject(error);
    },
  );

Upvotes: 0

AlphaZero
AlphaZero

Reputation: 11

This has to do with invalid JSON from the server side. You can use an online JSON validator like https://jsonlint.com/ to validate the JSON response.

Upvotes: 1

fathergorry
fathergorry

Reputation: 408

There might be an error in JSON. Axios return string when it fails to parse data into JSON. The common error in JSON is missing quotes in param names. Compare: JS: {x:"y"} JSON: {"x":"y"}

Upvotes: 0

Jakub A Suplicki
Jakub A Suplicki

Reputation: 4801

If the response is a string then you could use:

this.services = JSON.parse(response.data).data

else if it is a JSON object already (I think it might be - but get the actual data object from your response.data):

this.services = response.data.data

Then you could use v-for and get the title with {{service.title}}

Hope it helps.

Upvotes: 2

Related Questions