The property 'get' cannot be accessed because the axios module of vue__WEBPACK_IMPORTED_MODULE_0__ is undefined

Having some trouble with Vue and Axios - encountering the following error message:

[Vue warn]: Error in created hook: "TypeError: can't access property "get", vue__WEBPACK_IMPORTED_MODULE_0__.default.axios is undefined"

Here's the code snippet:

Api.service.js

import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
import JwtService from "./jwt.service";

const ApiService = {
    init() {
        Vue.use(VueAxios, axios);
        axios.defaults.baseURL = "http://hyper.test/api";
    },
}

BannerDataService.js:

import ApiService from "../api.service";

class BannerDataService {
    constructor() {
        
    }

    all() {
        return ApiService.get('site/banners')
    }

    get(id) {
        return ApiService.get(`site/banners/${id}`)
    }
}

export default new BannerDataService();

Index.vue:

getBanners() {
            BannerDataService.all().then(response => {
                console.debug(response)
            }).catch(err => {
                console.debug(err)
            })
        }

Error message in console:

[Vue warn]: Error in created hook: "TypeError: can't access property "get", vue__WEBPACK_IMPORTED_MODULE_0__.default.axios is undefined"

Answer №1

For the file Api.service.js, it is recommended to create an instance of axios directly without relying on it as a plugin :

import axios from 'axios';

const ApiService = () =>
  axios.create({
    baseURL: 'yourbaseUrl',
    withCredentials: false,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
   
  });

export default ApiService ;

In the BannerDataService.js file, make sure to call ApiService as a function using parentheses like ApiService().get(...)

import ApiService from "../api.service";

class BannerDataService {
    constructor() {
        // ApiService.setHeader();
        // ApiService.adminScope();
    }

    all() {
        return ApiService().get('site/banners')
    }

    get(id) {
        return ApiService().get(`site/banners/${id}`)
    }
}

export default new BannerDataService();

This approach mentioned above is independent of any specific UI library or framework.

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

Tips for storing HTML form data in a local JSON file without the need for PHP or Node.js dependencies

I'm interested in saving any information panel in an HTML file to a local JSON file. For example, if there are blocks like this: <div class="panel"> <div> <input type="text" name="producttype" id=&q ...

The declaration for "Control" is not present, possibly being restricted by its protection level

I'm really struggling to get the jQuery datepicker working in ASP.NET. I've tried various examples, but nothing seems to work for me. Even though I'm fairly new to ASP.NET, I am learning quickly! Here is the script I am trying to use: < ...

Increasing the top padding of a resized iframe thanks to iframe-resizer

Currently, I am utilizing the remarkable iframe-resizer library to resize an iFrame while keeping it in focus. The challenge I am facing is my inability to figure out how to include additional padding at the top of the iFrame once it's resized. The ...

Obtaining an XML element within an XSLT transformation

I need to retrieve the value of an XML element within XSL. Although my JavaScript is able to select one XML document, there are elements in other documents that I also require. I am uncertain if this task is feasible or if my syntax is incorrect. This is ...

Creating personalized hooks that rely on React query requests

Utilizing a series of custom hooks, I am able to fetch data and perform various calculations based on that data. One particular hook calculates the total amount that should be set aside monthly for future expenses, using the output from previous data-fetch ...

Prevent AJAX request while in progress?

I've made some adjustments to a jQuery Autocomplete plugin, which now retrieves a JSON object from a MySQL database instead of an array. However, I've noticed that each time I click on the input field, it triggers a new request, even if it&apos ...

tips on assigning a unique ID to an item in a firebase database collection

My code is structured like this: const userCollectionRef = collection(db, 'users'); Then I add data using the following method : const addInfoToDataBase = async () => { checkLike(); await addDoc(userCollectionRef, { likePost: us ...

Advanced jQuery Autocomplete with Nested Ajax Requests

I am currently developing a feature that allows users to search for albums using the Spotify Metadata API. The main functionality is working well, but I'm running into an issue with retrieving album cover art when making nested calls. This seems to be ...

What is the best way to iterate through an array of images and upload them individually, ensuring that they do not have duplicate names

In my current code snippet, I am working with an array of images called images and uploading each image within that array. Everything seems to be working correctly, but I am encountering a minor issue where all the uploaded images end up having the same na ...

What causes the updated value to be appended to an array when using the spread operator to modify an existing property's value?

In my state, I have an array of objects: const initialState=[{a:1},{b:2},{c:{d:3}}] const [state,setState]=useState(initialState) My goal is to modify the value of b to 5 within my event handler: function changeBToFive() { setState((state) => [ ...

The components for my children are not being displayed within the Drawer component in Material UI and React

Why are the Material UI components and other project components not displayed when I use my DrawerForm component? List of dependencies: react: 18.2.0 react-dom: 18.2.0 @amcharts/amcharts5: 5.3.6 @mui/icons-material: 5.11.11 @mui/material: 5.11.12 Code s ...

Create a JavaScript function that adds cells to a table, each containing an input field and a corresponding

I successfully developed a function that appends a table with rows and cells, then fills those cells with data from an array. However, I am now faced with the challenge of modifying it so that the generated cells contain an input field where the value= att ...

Tips for creating animations with JavaScript on a webpage

I created a navigation bar for practice and attempted to show or hide its content only when its title is clicked. I successfully toggled a hidden class on and off, but I also wanted it to transition and slide down instead of just appearing suddenly. Unfort ...

Exploring the potential of Angular JS and gapi in building a seamless routed

I'm facing a similar challenge as described in this question. However, the key difference is that I require two controllers for two distinct routes, essentially representing two different tables: ../table1 and ../table2. Each table needs to fetch data ...

Transform pixel padding into percentage ratios

I've been searching through various discussions to find a solution, but none of them seem to fit my particular scenario. My issue involves a hyperlink with absolute positioning inside a div with relative positioning. The padding and margins are curre ...

Looking to encode/decode a JSON response in order to transfer it to a different webpage

Currently, I have a website application where I am required to pass a JSON response (in string format) across the site. To achieve this, I have been using a hidden type value and passing it upon the submission of a link/button which subsequently triggers a ...

Utilizing React Hook Form for Interactive Slider and User Input Controls

Whenever I move the Slider, I want to retrieve the same value as when I enter a new value in the Input field. However, the current setup is not functioning correctly. <StyledSlider {register(NAME ...

Having trouble with installing create-react-app for my_app using npm because it seems to be stuck on f

I've hit a roadblock while trying to create a react app on my 2011 MacBook Pro. To start, I downloaded the latest version of Node from their official website. Following the instructions from React documentation, I ran the following commands: npm uni ...

Passing the unique identifier of a record in NextJS to a function that triggers a modal display

I'm currently facing an issue with my NextJS component that displays a list of people. I have implemented a delete button which triggers a modal to confirm the deletion of a person, but I am struggling with passing the id of the person to be deleted. ...

Vue - Syntax error: Unexpected token, expecting "}."

I recently started working with Vue and have encountered a simple component issue. Sometimes, when I run npm run serve or save a file that is already being served, I receive the following error message: E:\Development\website\app>npm run ...