Guide to setting up an API service using Axios in VueJs

Trying my hand at creating an API service with this syntax:

apiservice.js

import axios from 'axios'
import * as users from '@/plugins/apiservice/modules/users';

const apiservice = axios.create({
  baseURL: process.env.VUE_APP_URL,
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Authorization: `Bearer ${localStorage.getItem('sessionToken')}`
  },
})
export default {apiservice, users};

users.js

import apiservice from "@/plugins/apiservice";

  const login = async (params) => {
    try {
      const result = await apiservice.post('/login', params);
      return result.data;
    } catch (error) {
      return error;
    }
  }
 
  export {login};

Component.vue

import apiservice from '@/plugins/apiservice';
const response = await apiservice.users.login(this.loginData);

Encountered an error when trying to enter data TypeError: plugins_apiservice__WEBPACK_IMPORTED_MODULE_2_.default.post is not a function

NOTE 1: A GET request was successful with a 200 response

NOTE 2: Using the exact login function within apiservice works perfectly

Answer №1

apiservice.js exports the axios instance as a subproperty of the default export with the key name "apiservice":

// apiservice.js
const apiservice = axios.create(/*...*/)
          👆         👇
export default {apiservice, users};

To access the axios instance, you must refer to this subproperty:

// users.js
import apiservice from "@/plugins/apiservice";
//...
const result = await apiservice.apiservice.post('/login', params);

Alternatively, you have the option of using a named export:

// apiservice.js
export const axiosInstance = axios.create(/*...*/)
// users.js
import { axiosInstance } from "@/plugins/apiservice";
//...
const result = await axiosInstance.post('/login', params);

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

Flawless Carousel - Flipping the Sequence

I am currently implementing Slick Carousel on a website that I am working on. One challenge I am encountering is trying to get the "slider-nav" to move in the opposite direction than it normally does. For instance, at the moment, the order goes like this ...

Is it best practice to use the AngularFirestoreCollection for updating Firestore items in AngularFire?

Within my application, I have a list that necessitates the use of an "or" condition. However, according to the documentation: "In this case, you should create a separate query for each OR condition and merge the query results in your app." Consequently ...

Using material-icons for cell rendering in ag-Grid with Vue

I am currently incorporating ag-Grid into a vuejs project. My goal is to render cells that display material icons, but unfortunately only the icon name appears instead of the actual icon: https://i.stack.imgur.com/9tV7B.png Below is the code for the &apo ...

Navigating through object arrays using a loop

I have multiple arrays within an object that I would like to iterate through using numeric values. This is necessary in order to assign them to different slots in an accordion loop. The JSON file containing the data looks similar to this (Pokemon used as a ...

Using AngularJS to add a unique custom class directive to each item in an ng-repeat loop

Can anyone help me figure out why the width of a div isn't being set dynamically using AngularJS? <ul id="contents"> <li ng-repeat="content in contents"> <div class="content_right custom_width"> <div class="title"> ...

Unable to retrieve jwt token from cookies

Currently, I am developing a website using the MERN stack and implementing JWT for authentication. My goal is to store JWT tokens in cookies. Despite invoking the res.cookie function with specified parameters (refer to the code below), I am facing difficul ...

When multiple instances are present, the functionality of dynamically generated jQuery functions ceases to operate effectively

I've developed a chat application similar to hangouts where clicking on a user generates the chat div. One feature I have is allowing users to press enter in a textarea to send text, but when multiple dynamically generated jQuery functions are present ...

Guide to transferring information from a Complex Form in nodejs and express to MongoDB

I am a newcomer to node.js and express. Currently, I am working on creating a Business Card Generator application using nodejs, express, and MongoDB. I have set up a multi-step form in ejs and now I am looking for guidance on how to store the input data ...

The function cannot be called because the type does not have the appropriate signature for invoking. The specific type lacks compatible call signatures, as indicated

Encountering an issue while attempting to utilize a getter and setter in my service, resulting in the following error message: Cannot invoke an expression whose type lacks a call signature. Type 'Boolean' has no compatible call signatures 2349 t ...

Distinguishing Between Global and Local Variables

let picture = document.getElementById('image1'); function moveLeftArrow () { picture.style.left = parseInt(picture.style.left) - 5 + 'px'; } This code is designed to allow users to move images using the arrow keys. Interestingly, th ...

Manifest JSON not displaying Add to Home Screen prompt

I am trying to implement the prompt for adding to the home screen using manifest.json, but I am facing an issue where the prompt is not showing up even though my PWA score in the audit is 100%. Below is the structure of my dist folder: https://i.sstatic. ...

Troubleshooting: React js component fails to render

I've been trying to implement React using the code below, but I'm unable to see any HTML elements in the browser. Surprisingly, there are no errors showing up in the console. <!DOCTYPE html> <html> <head> <t ...

Implementing jQuery in Ionic 3: A Step-by-Step Guide

I am attempting to display an external website within a div element using jQuery in Ionic 3. TS: export class HomePage { constructor(public navCtrl: NavController) { $('#loadExternalURL').load('http://www.google.com'); ...

What is preventing Protractor from detecting Angular on a site that has been automatically initialized with Angular?

Whenever I try to utilize browser.get() in my code, I encounter the following error: Error: Angular could not be found on the page http://localhost:5000/#/login debug=timing&saveLogs=true&displayAll=true : angular never provided resumeBootstrap A ...

Retrieve the Most Recent Matching Date within an Array

In my mongoDB database, I am searching for datasets with expired date values. When I say expired, I mean that the timestamp of the last element in an array is older than a certain interval from the current timestamp (determined by a category). Each datase ...

Retrieving information from a JSON file and dynamically displaying it on an HTML page using JavaScript

I've been working on pulling data from a JSON file to display on my website. Following this helpful guide at: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON, but unfortunately, I'm facing an issue where nothing is showing ...

When using a Mac, Vue has trouble starting on port 80 and displays an error message

https://i.sstatic.net/mrd6D.png When starting the Vue project on macOS, the port number is set to 80. However, it appears that ports below 1024 are disabled on Mac computers. How can this issue be resolved? I'm seeking assistance in enabling the pro ...

Tips for preventing the creation of an element in AngularJS

When working with Angular, I encountered an issue with creating an <iframe> element only upon user interaction. Initially, I simply placed the element on the page and used the ng-if directive to bind its presence to a boolean in my model. However, I ...

What is the best way to utilize $.post() to send a combination of a javascript object and form

I'm having trouble sending a JavaScript object along with form data using the shorthand method $.post(). I want to combine these two, but it's proving to be difficult. Additionally, I need to know how to retrieve the form data on my PHP page. An ...

Exploring the functionality differences between mouse wheel tilt and scroll in JavaScript with scrollTop

Did you know that some computer mice come equipped with a scroll wheel that can tilt both left and right? This feature allows users to navigate through Google's piano roll app, which can be accessed here (source code available here). I am working to ...