Vue.js does not return JSON data from Axios, only a string

I am facing an issue with axios as it is returning a string instead of JSON format. I need some help to understand why this is happening.

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

On searching online, I found out that response.data should return only the parsed json data, but in my case, {{services}} displays the following :

{ "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 :)

Answer №1

If the result you receive is a string, you can implement the following code:

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

If it happens to be a JSON object already (which I suspect may be the case, but ensure that you're extracting the actual data object from your response.data):

this.services = response.data.data

Afterwards, you can utilize v-for to iterate through and retrieve the title using {{service.title}}

I hope this advice proves beneficial for you.

Answer №2

The issue at hand is related to receiving invalid JSON from the server. To ensure the validity of the JSON response, you can utilize an online JSON validator such as https://jsonlint.com/.

Answer №3

JSON errors can occur when Axios is unable to parse data properly, resulting in it returning a string instead of valid JSON. One common mistake in JSON formatting is omitting quotes around parameter names. For example: JavaScript: {x:"y"} Valid JSON: {"x":"y"}

Answer №4

To address this issue, you can utilize an interceptor in your code.

  const client = new Axios({});

  // Modify data type if it is a 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);
    },
  );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Submitting a nested JSON body in ASP MVC

I'm currently struggling to send a nested JSON body to an API, and I've tried a few different approaches without success. The JSON values are sourced from multiple models, making it quite complex for me to handle. Any assistance or guidance on th ...

Using a JSON object in conjunction with an AJAX call to retrieve an array

Having trouble working with the array returned from an ajax call. The array is encrypted using json and looks like this: while ($found_course = mysql_fetch_assoc($sql)) { $info[] = array( 'code' => $found_course['course_cod ...

Add AngularJS to an AJAX call when the user clicks on it

I'm currently exploring the SoundCloud API and looking to implement a feature where users can add a song to the page by clicking on it from the search results. I've decided to utilize Plangular, which you can find more information about here. How ...

New to JSON: Why is my variable returning as undefined?

Embarking on my first JSON project has brought some challenges that I am struggling to overcome. Here's the task at hand. I have created a basic scraper using Apify.com to extract data from a specific website. The data is presented in JSON format, an ...

Error: [BITFIELD_INVALID_RANGE]: The bitfield flag or number entered is not valid: 3214336

Currently working on a Discord Dashboard project, but encountering an unusual error: Invalid bitfield flag or number 3214336. This issue arises when attempting to retrieve the guilds that a user has MANAGE_GUILDS permission for. Below is the snippet of my ...

Dynamically assigning a name to a variable through code

Is there a quicker way to complete these 100 tasks? variable_1 = 1; variable_2 = 2; variable_3 = 3; ... variable_100 = 100; I attempted to use the following code: for(var i = 1; i <= 100; i++) { variable_ + i = i; } However, I encountered an e ...

Using JavaScript to close a menu when clicking outside of it

I am currently working on enhancing a menu with a basic functionality. The goal is to toggle the menu between showing and hiding when a button is clicked, managed by a CSS class using JavaScript. However, I have encountered an issue when attempting to com ...

Encountering a 405 Error Code while attempting to upload files with ng-file-upload

In an attempt to incorporate a file upload feature using ng-file-upload, I stumbled upon an example here that served as my reference. Despite everything appearing to function correctly, the issue arises when attempting to upload the file to my local webse ...

Testing API route handlers function in Next.js with Jest

Here is a health check function that I am working with: export default function handler(req, res) { res.status(200).json({ message: "Hello from Next.js!" }); } Alongside this function, there is a test in place: import handler from "./heal ...

Securely encoding information with PHP and decrypting it using JavaScript

I'm currently working with 2 servers. My goal is to generate a pair of keys, store the private key in local storage, and send the public key to my PHP server. The main objective is to encrypt data using the public key in PHP and decrypt it using Jav ...

The stateless components' onClick event that manages a prop within the Component

My concern lies with a stateless component named EmailItem: I aim to assign it a new prop via a function when clicked. <EmailItem key={i} onClick={// the onClick function here} emailData={email} read={false} /> The desire is for the value of the rea ...

The issue of execution order in JavaScript Recursion with promises

In the process of developing a method for creating markup to be used in a web app's off-canvas navigation. One of the challenges I am facing is making an asynchronous callback to another service that provides children nodes for the parent menu node (r ...

Is the file corrupt using node.js?

Looking for ways to determine if a file is corrupted using node.js? I have attempted various File System methods, such as fs.readFile, fs.open, and fs.access, but all of them are showing an OK status. However, I am confident that my file is corrupted base ...

Discord bot struggling to reach every user in the server

After creating a discord bot with Discord.js, I was able to retrieve all the users from my server. However, lately I noticed that it is only returning 59 members out of the 300+ in total. I want to ensure that I am able to access all the users as before. ...

Implementing a personalized Angular filter with an indexOf condition

As a beginner in the world of computers, I am attempting to create a customized filter for an AngularJS application. My objective is to search through a string of integers (cultivos.age) and retrieve the item if the string meets the mes.age condition. I h ...

How can we ensure that React state remains unaltered when modifying an array set to state?

Hope you're having a wonderful day! I'm encountering a significant problem with React. I have a state that contains an array. Within a function, I create a copy of the state in a new variable. However, any modifications made to this new variable ...

Unlocking the Chrome performance tool summary using SeleniumDiscovering the Chrome performance tool

I'm looking to utilize the Chrome performance tool for analyzing my website and then extract a summary of the results using Selenium WebDriver in Java. Despite extensive searching, I haven't been able to find a suitable solution yet. To give you ...

Modify the colors of names within an array of point names and their corresponding y values using Highcharts

I am trying to customize the color for each point in an array based on its name and y value. This is what I have so far: (function(H) { H.wrap(H.Series.prototype, 'getColor', function(proceed) { this.color = generateColorForString(this.na ...

What is behind the peculiar reaction when checkboxes are used in React?

In this demo, what is causing the button to disable only after both checkboxes have been checked? Is the button not initially displayed as disabled due to the way state behaves in react? The example consists of two checkboxes: I have read and agree to te ...

Customize your file input with Bootstrap 4 using bs-custom-file-input and create a Symfony 5 collection with dynamic upload fields

The issue of not having a label for the chosen filename in a bootstrap 4 upload field has been resolved using the plugin https://github.com/Johann-S/bs-custom-file-input You can utilize "bs-custom-file-input" to showcase the selected filename in the boots ...