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

Venom Bot encounters issue with sending files, displaying "Error processing files" message

When attempting to send a PDF in the code snippet below, I encountered the following error: app.post('/send-pdf',[ body('number').notEmpty(), ], async (req, res) => { const errors = validationResult(req).formatWith(({ msg }) =&g ...

Testing nested mocked functions can be achieved by setting up the necessary mocks

How can I create tests for mocked functions within a mocked function? My goal is to verify that my publish mocked function is called only once. jest.mock('amqplib', () => ({ connect: jest.fn(() => Promise.resolve({ createChannel: jes ...

Ways to enhance the type definitions for a built-in HTML element in Vue.js?

Imagine having an element that wraps around an input and inherits all of its properties, along with some extras. In React, you would define this as: interface ExtendedInputProps extends React.ComponentPropsWithoutRef<'input'> { some: T ...

Can the `lang` attribute be used in a `style` tag to specify the CSS preprocessor language for VueJS? Are there any disadvantages to using this method?

Occasionally, I notice people incorporating code like this: <style lang="scss"> ... </style> <style lang="stylus"> ... </style> I checked the documentation for the style tag and found that lang is not a valid a ...

Utilizing jQuery to eliminate a script function from an external webpage

Currently, I am utilizing a ColdFusion script to load an external page within the container tag. This external page contains a sorting function defined as: function sorting(sortid). However, this function's sorting criteria constantly leads to errors ...

Unusual behavior being exhibited by the background in an HTML5 canvas

I have an 800 by 100 image for the background and I'm trying to extract sections from it (like a sprite sheet) in order to create a background. I believe this method is efficient and allows me to experiment and learn how to generate backgrounds in the ...

Automated tool for generating random JSON objects

Looking for a tool that can generate random JSON objects? I'm in need of one to test my HTTP POST requests and incorporate the random JSON object into them. Any recommendations? ...

Replicate form element

I am having trouble duplicating form items Greetings to all. I have a form and I'm looking to add a button that allows users to duplicate fields each time they click on it. Here is my form: <v-layout v-for="(phone, index) in people.phones" :key=" ...

"Learn how to seamlessly submit a form and display the results without the need to refresh the

Here is the form and result div: <form action="result.php"> <input type="checkbox" name="number[]" value="11" /> <input type="checkbox" name="number[]" value="12" /> <input type="checkbox" name="number[]" value="13" /> <input t ...

Exploring the intricacies of initializing a JavaScript function

I recently inherited a large JavaScript file from a previous developer, and I'm trying to decipher some of the key sections. Here is the complete code: $(function () { var homepage = (function () { // Main functionalities are defined he ...

Creating a predictive text feature using AngularJS and jQuery

Currently, I'm developing a web application that utilizes: JQuery AngularJS Kendo framework Specifically, I am tasked with implementing an auto-complete feature using Kendo on an input text field. Initially, my approach was to target the inp ...

Exploring test suite pathways while utilizing ArcGIS JSAPI as an alternative loader within the Intern framework

I have been developing an application using the ArcGIS Javascript API and incorporating tests with Intern. While working on Windows 7 under IIS, I encountered some challenges but managed to overcome them by following the Intern tutorial and referring to so ...

Steps for instructing Google Maps to identify the location of a provided Google Maps URL

Is it possible to extract longitude and latitude data from a shared URL and place them into a marker? For example, users might copy and paste the 'Share' URL from Google Maps. For instance: or Direct Location: https://www.google.co.nz/maps/plac ...

The Ajax call is failing to trigger the success function

Can anyone assist me? My success function isn't working properly. The beforesend is functioning correctly and I've verified the variable s. It has a true value before the ajax call, so all validations are correct. Please take a look... function ...

Tips on altering the input content in React Js?

I am currently working on developing a component for my application where I want to create a button that, when clicked, opens an input field. After entering text into the input field and clicking the button again, another input field should appear, and so ...

Discovering an element within an HTML response using jQuery AJAX

Check out the code snippet below: ajax_obj = $.ajax( { data: data, success: function(answer) { console.log(answer); console.log($('#table_conferences_tbody', answer).html()); ...

Switch the custom audio control button on and off within a v-for loop

I have implemented a unique audio play/pause button in my Vue app for a list of audios. Here is how it looks: <div v-for="(post, p) in post_list"> ... ... ... <v-avatar v-if="!is_played" color="#663399" ...

using jquery to retrieve the current time and compare it

This is the code I currently have: var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() aler ...

Unable to showcase the chosen option utilizing select2

Utilizing angular-ui's select2 directive has been a bit of a challenge. While the functionality is there, I've encountered an issue where the selected value isn't being displayed properly due to my implementation workaround. <select ...

What could be causing my for loop to not function properly within the ngOnInit lifecycle hook?

I am attempting to create a nested loop structure in order to access an array that is inside an object within an array of objects, and then store this data into a new array. My issue arises as the first loop executes successfully but the second one does no ...