The v-data-table is unable to fetch the user list information from the API using Axios

How can I solve the issue of displaying "No data available" in the user list data table on my userDirectory page?

I have created a userDirectory page with a subheader and a data table from Vuetify, but it seems to have no data available.

<template>
  <div class="userDirectory">
    <v-subheader class="d-flex justify-space-between align-center">
      <h3>User Directory</h3>
    </v-subheader>
    <v-row>
      <v-card>
        <template>
          <v-data-table :headers="headers" :items="users" :items-per-page="5" class="elevation-1"></v-data-table>
        </template>
      </v-card>
    </v-row>

  </div>
</template>

<script>
import axios from 'axios'
export default {
  data: () => ({
    headers: [
    {
            text: 'User ID',
            align: 'start',
            sortable: false,
            value: 'u.id',
          },
          { text: 'Created At', value: 'created_at' },
          { text: 'Email', value: 'email' },
          { text: 'Is Premium', value: 'is_premium' },
          { text: 'Goal', value: 'goal' },
          { text: 'Fitness Level', value: 'fitness_level' },
          { text: 'Profile Completed', value: 'profile_completed' },
          { text: 'Accepted Health Warning', value: 'accepted_health_warning' },
          { text: 'Role', value: 'roles_list' },
    ],
    users: [],
  }),
  methods: {
    async loadUsers() {
      axios.get('https://somehost/api/admin/getUserList', { headers: {Authorization : 'Bearer ' + 'token' }})
      .then(res=> console.log(res))
  .catch(err=> console.log(err))
    }
  },
}
</script>

<style scoped>

</style>

Furthermore, I have an API file that successfully retrieves the data using a GET request in Thunder Client with a bearer token, but encounters issues in Vue. Here's the code snippet:

const { response } = require("express");
const pool = require("../../config/database");

async function listUsers() {

    let sqlquery = `select
                        u.id, 
                        created_at,
                        email,
                        is_premium,
                        goal,
                        fitness_level,
                        profile_completed,
                        accepted_health_warning,
                        group_concat(r.name) as roles_list
                    from users u
                    left join user_role ur on ur.user_id = u.id
                    left join role r on r.id = ur.role_id
                    group by u.id;`
    return new Promise((resolve, reject) => {
        pool.query(sqlquery,
            (error, results) => {
                if (error) {
                    return reject(error)
                }
                return resolve(results)
            })
    })
}

module.exports.listUsers = listUsers;

Answer №1

Have you ever needed to utilize the loadUsers function in your code?

<script>
export default { 
  // ... data
  created() {
    this.loadUsers();
  }, 
  methods: {
    loadUsers() {
      axios.get('https://somehost/api/admin/getUserList', { headers: {Authorization : 'Bearer ' + 'token' }})
      .then(res=> {
          // populate the users array with the result
          this.users = res;
       })
      .catch(err=> console.log(err))
    }
  },
}
</script>

Answer №2

Just as Matt mentioned, be sure to invoke your function or else nothing will happen.

created() {
    this.loadUsers();
  },

If you try calling it now, you may encounter a CORS error due to the server API restricting access and blocking the request. This is quite common.

Based on your file where you imported express, it seems like you are using Express (Node.js).

To resolve this, you can install the node-cors package by running this command:

npm install cors

For documentation, visit: https://expressjs.com/en/resources/middleware/cors.html

In your app.js file, include the following:

const app = express()
const cors = require('cors');

app.use(cors({
    origin: 'https://mywebsite.com'
}))

The 'origin' key authorizes your Vue.js app. If your Vue app runs on localhost:3000 or on a domain like mondomaine.com, adjust accordingly:

origin: 'http://mondomaine.com'

This solution applies for online domains.


If you're working on localhost, you'll need to set up a proxy in vue.js, which isn't complicated.

In your scenario, replace the URL when making the GET request:

axios.get('/api/admin/getUserList', ... // keep the existing code

Essentially, the GET call will now be directed to localhost:1000/api/admin/getUserList, resulting in the same domain request without CORS issues.

To implement a proxy, follow these simple steps:

devServer: {
    proxy: {
      '^/api/*': {
        target: 'https://somehost/'
      }
    }
  },

Your call to localhost:1000/api/admin/getUserList will be intercepted by the ^/api/* proxy and redirected to https://somehost/api/admin/getUserList

Remember to restart your Vue server after any changes in vue.config.js.

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

Exploring TypeORM: Leveraging the In() function within @ManyToMany relationships

There are two main characters in my story: Hero and Villain (their profiles are provided below). How can I utilize the Encounter() method to identify all instances where the Hero interacts with the Villain based on an array of Villain IDs? I am seeking a ...

Display a unique button and apply a strike-through effect specifically for that individual list item

I've encountered an issue with my code that is causing problems specifically with nested LI elements under the targeted li element: $('#comment-section .comment-box a#un-do').hide(); $('#comment-section ul li[data-is-archived="true"]& ...

Is there a way to enhance the Download File dialog with an additional option?

I want to develop an extension for a specific file type, and I'm interested in including a "Send to MyAddonName" feature in the download file dialog, alongside the "Open with" and "Save file" options. Just to clarify, I don't mean the Download Ma ...

Issue with Webpack in vue.js project when incorporating sasssass causing errors

I am new to Vue.js and webpack, and I'm not sure if the issue lies with the packages or my own mistake. Steps to replicate the problem: Create a new Vue project using the webpack template ~ vue init webpack sass-test ? Project name sass-test ? Proj ...

Retrieve the ID of the image element using Jquery from a collection of images within a div container

I'm encountering a simple issue that I can't seem to solve. I am working on a basic slider/gallery with the following functionalities: 1) "If button 1 is clicked, image one will appear." 2) "Clicking on button 2 will make IMAGE 1 slide left and I ...

Various redirects based on multiple referrers

Here is the code I have for redirecting based on the referer: document.addEventListener('DOMContentLoaded', function() { console.log(isMobile); var referrer = document.referrer; if(referrer.indexOf('site1.com') !== -1 || referrer ...

SailsJS - handling blueprint routes prior to configuration of routes

I am trying to configure a route in my config/routes.js file as shown below '*' : { controller: 'CustomRoutes', action: 'any', skipAssets:true } The CustomRoutes controller is responsible for handling custom routes. Th ...

Creating dual graphs simultaneously in Rickshaw

Can two graphs with different Y axes be plotted together? I have data on page views organized in a stacked area chart by referrer, and I would like to overlay a line graph depicting the number of actions over time. Although I already have both graphs ind ...

Update the browser value using AJAX without the need to refresh the page

After retrieving a value from an XML file using ajax jquery, I encountered an issue. When I change the value in my XML file, it does not automatically update in the browser. <?xml version="1.0"?> <count><number>5</number></count ...

The put method is not recognizing the Axios callback function

Having an issue with Axios callback not working when updating a MySQL database. The data gets updated successfully, but the callback function doesn't work. Strangely, post, delete and get callbacks are working fine. Here is the code snippet: Frontend ...

Include a search button within the search box of the Custom Search Engine

Can anyone help me with adding a search button to my HTML code? I've tried implementing it, but when I try to search something on a website like YouTube, the results show up without displaying my search query. How can I fix this issue and what changes ...

Verifying the presence of a popover

Utilizing bootstrap popover in my project, I am encountering an issue where the target variable may not always exist on the page. Currently, I am displaying the popover using the following code snippet - target = $('#' + currentPopoverId.data(& ...

Trigger an event within a linked component

I've been working on a connected component where I'm attempting to dispatch the clear action from. Here's a snippet of the code: import {createElement} from 'react'; import reduce from 'lodash/fp/reduce'; import {connect ...

Eternal operation of the Next.js server

I am in need of creating a server that runs continuously to monitor the database data and execute necessary actions based on that information. While I am aware that this can be achieved using a simple Node.js server, I am curious to know if it is also po ...

What significance does comparing two arrays hold in the realm of Javascript?

While working in my node.js REPL, I have created 4 arrays: a = [1,2,3], b=[], c=[4,5], d=null (although d is not actually an array). I decided to compare them directly like this: > b = [] [] > a > b true > b > a false > a > c false & ...

Vue component with a variable number of rows, each containing a variable number of input fields

I am currently working on creating a form that can have a variable number of steps. Users should be able to add an additional step by clicking a button. Each step will contain some input fields and buttons to dynamically create more input fields. For inst ...

How can I efficiently map an array based on multiple other arrays in JavaScript/TypeScript using ES6(7) without nested loops?

I am dealing with 2 arrays: const history = [ { type: 'change', old: 1, new: 2 }, { type: 'change', old: 3, new: 4 }, ]; const contents = [ { id: 1, info: 'infor1' }, { id: 2, info: 'infor2' }, { id: ...

Having issues with my JavaScript code - it just won't function

I am having an issue with my JavaScript code. I don't receive any errors, but when I click the submit button, nothing happens. I have followed a video tutorial and watched it twice, but I can't seem to figure out what is wrong here. Here is the ...

Stop calling API after a certain time period in vue.js

Imagine a situation where the GET API call requires approximately 1 minute to retrieve the most recent data after being updated by INSERT/UPDATE API calls. Suppose a user modifies certain fields in the user interface and triggers an UPDATE call, which the ...

Exploring the Functionality of Cookies in Nuxt 3 API Endpoints and Middlewares

Can cookies be utilized on the server side in Nuxt 3? For instance, I need to set a cookie in an API and then access its data in middleware: // ~/server/api/testApi.ts export default defineEventHandler(event => { /* setCookie('myCookie', ...