Vue.js is displaying API data in the browser's console, but it is not appearing on the webpage

I am currently learning about API design and attempting to make an API call that retrieves data from an online API server using the vue.js project through CLI. While I can see the results in the browser console, I'm encountering issues with displaying the actual data on the webpage. I have researched similar problems but none seem to address the specific difficulties I am facing with Vue. Despite spending days looking into it, I haven't been able to pinpoint the problem. It's frustrating to admit defeat, especially when I suspect it may be a basic mistake causing the error. Here is the relevant code:

<template>
  <div class="health">
    <p>{{response}}</p>
  </div>
</template>
<script>
import axios from "axios";
export default {
  name: "HelloHealth",
  data() {
    return {
      response: ""
    };
  },
  mounted() {
    axios({
      method: "GET",
      url:
        "https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random",
      headers: {
        "content-type": "application/octet-stream",
        "x-rapidapi-host": "matchilling-chuck-norris-jokes-v1.p.rapidapi.com",
        "x-rapidapi-key": "5788793819msh9c9b16c2298d826p1e5fefjsn3d5bde507db6",
        accept: "application/json"
      }
    })
      .then(response => {
        console.log(response.data);
      })
      .catch(error => {
        console.log(error);
      });
  }
};
</script>

The console displays these results for the code:

https://i.sstatic.net/8jTnP.png

Could someone please assist me in identifying my mistake? Thank you for your help.

Answer №1

Your current setup does not contain any stored response data within the response property. Instead of directly invoking the API within the mounted() lifecycle method, a more organized approach would be to call the API within a separate method from mounted(). This ensures better coding practices. Here's how you can implement this:

import axios from "axios";
export default {
  data() {
    return {
      response: ""
    }
  },
  methods: {
    fetchResponseData() {
      axios({
        method: "GET",
        url:
          "https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random",
        headers: {
          "content-type": "application/octet-stream",
          "x-rapidapi-host": "matchilling-chuck-norris-jokes-v1.p.rapidapi.com",
          "x-rapidapi-key": "5788793819msh9c9b16c2298d826p1e5fefjsn3d5bde507db6",
          accept: "application/json"
        }
      })
        .then(response => {
          this.response = response.data;
          console.log(this.response); // access response data
        })
        .catch(error => {
          console.log(error);
        });
      }
  },

  mounted() {
    this.fetchResponseData();
  }
}

Thank you.

Answer №2

Ensure that you assign a value to this.response other than just an empty string "". After the successful Axios call within your mounted() method, make sure to set the response like this:

 .then(response => {
     this.response = response.data;
 })

If you need assistance with consuming APIs and incorporating data into Vue, Vue's documentation provides a helpful guide at: https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html

Answer №3

.then(res => {
      this.res = res.data;
      console.log(this.res); //retrieving response data
    })

The scope of the response obtained from axios is limited. It can only be accessed within the then function. Make sure to assign the axios response to the component's response.

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

Generating grid-style buttons dynamically using jQuery Mobile

I am in need of assistance to create a dynamic grid using jQuery Mobile. The grid should consist of buttons with either 'onclick' or 'href' functionality. The number of buttons should be generated dynamically at runtime. Specifically, I ...

Exploring the functionality of useRoute within a composable in Vue

I am working on a file store/service.js and I am trying to incorporate a router. This is what I have attempted so far: import { useRoute } from 'vue-router'; const router = useRoute(); function exceptionHandler(error) { if (error.response.sta ...

Compile a roster of service providers specializing in unit testing imports

Recently joining a new team that works with Angular, they asked me to implement unit testing on an existing project built with Angular 8. After researching the best approach, I decided to use Karma + Jasmine for testing. I set up a .spect.ts file structure ...

What could be causing the issue of images not loading in Chrome while they are loading perfectly in Mozilla when using CSS3?

Recently, I dove into a project utilizing react with webpack, and everything was smooth sailing until I encountered the CSS hurdle. Despite successfully configuring webpack, trouble brewed when it came to styling. Specifically, setting the background image ...

What could be the reason the server actions in nextjs 13 are not functioning correctly?

I am currently working on a project to retrieve data from mockapi.io, a mock API. However, I am encountering an issue where the fetched data is not displaying in the browser. There are no visible errors, and the browser window remains blank. Interestingly, ...

PHP Ajax file uploads can be tricky, as they often result in the frustrating "undefined

Encountering issues with submitting file through ajax. Despite following instructions from various sources, the formdata does not seem to contain the file resulting in an 'undefined index 'image'' error. <form enctype: 'multip ...

Displaying a text in a Django template as a JSON entity

I am currently facing a challenge with an angular app that sends JSON data to a Django backend. The Django application saves the JSON data into a database and later retrieves it to send it back to the angular app. However, I am struggling to get this entir ...

Tips for transferring properties from one React component to another React component

I need to figure out how to activate a button in a modal when text is entered into an input field. The form is part of a different class and is utilized within a parent class. How can I pass an onChange method to my form component? Check out the code for ...

Redirecting in Laravel after making an AJAX request results in a "Method Not Allowed" error

I've encountered an unusual problem with my web application built using Vue 3 and Inertia, which includes forms. So, here's the scenario: If I have two browsers open and log out in one, then trigger an Ajax request in the other, it goes through t ...

When a URL is triggered via a browser notification in Angular 2, the target component ceases to function properly

Whenever I access a URL by clicking on a browser notification, the functionality of the page seems to stop working. To demonstrate this issue, I have a small project available here: https://github.com/bdwbdv/quickstart Expected behavior: after starting t ...

How can I retrieve the height of a hidden image in Internet Explorer?

I am encountering an issue with images that have been set to display:none. I am using javascript (document.getElementById('elem').height) to retrieve the height/width of these images. While this method works in most browsers, IE is reporting th ...

Tips for determining if an HTMLElement has already been created

One issue I'm facing is with a third party component that emits an "onCellEdit" event and passes a cell element as a parameter. My goal is to automatically select the entire text in the input element generated inside this cell when the event occurs. ...

Converting Xpath into a CSS selector

Having a difficult time converting the Xpath "//form[@id='giftcard-form']/div[3]/div/button" to CSS. I've tried using it for my Selenium JS but it's not working for some reason. Managed to convert an easier one successfully and use it i ...

What is the best way to prevent the dropdown function in a selectpicker (Bootstrap-Select)?

Is there a way to completely disable a selectpicker when a radio button is set to "No"? The current code I have only partially disables the selectpicker: $("#mySelect").prop("disabled", true); $(".selectpicker[data-id='mySelect']").addClas ...

Construct a string by combining the elements of a multi-dimensional array of children, organized into grouped

My task involves manipulating a complex, deeply nested array of nodes to create a specific query string structure. The desired format for the query string is as follows: (FULL_NAME="x" AND NOT(AGE="30" OR AGE="40" AND (ADDRESS ...

Delivering static files with NGINX and Vue.js

I've set up a basic node server to serve a Vue.js application that I built. The server is currently running on localhost:3000 Nginx is configured to listen on port 80 The application has been deployed on the local IP address. Nginx Configuration: ...

Access all areas with unlimited password possibilities on our sign-in page

I have set up a xamp-based web server and installed an attendance system. I have 10 users registered to log in individually and enter their attendance. However, the issue is that on the login page, any password entered is accepted without showing an error ...

Update the value of a Vue tree select component using JavaScript

I'm working on a school project using plain JavaScript and needed a tree view select with multiple layers. After extensive searching, I stumbled upon this tool. It's working smoothly, but the one thing that has me stumped is how to change its va ...

Error: Undefined object while trying to access 'injection' property

After updating to React 16.x, I encountered the following error: Uncaught TypeError: Cannot read property 'injection' of undefined at injectTapEventPlugin (injectTapEventPlugin.js:23) at eval (index.js:53) at Object.<anonymous> ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...