One file successfully imports a dependency, while the other file does not seem to recognize it

I'm diving into the world of Vuex, exploring how to create an auth module. I came across some examples that I'm trying to implement, but I've hit a roadblock when attempting to use axios in my store. My store is structured with separate files for index, actions, getters, etc.

The login action works fine when it's placed in the actions section of store/index.js. However, when I moved it to store/actions.js, I encountered an error stating that axios is undefined.

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
// import example from './module-example'

Vue.use(Vuex)

/*
 * If not building with SSR mode, you can
 * directly export the Store instantiation
 */
import state from './state'
import getters from './getters'
import mutations from './mutations'
import actions from './actions'


export default function(/* { ssrContext } */) {
  const Store = new Vuex.Store({
    modules: {
      // example
    },
    namespaced: false,
    getters,
    mutations,
    actions,
    state,
    // enable strict mode (adds overhead!)
    // for dev mode only
    strict: process.env.DEV,
  })

  return Store
}

store/actions.js

export default {
  login({ commit }, user){
    return new Promise((resolve, reject) => {
      commit('auth_request')
      axios({ url: 'http://localhost:3000/login', data: user, method: 'POST' })
        .then(resp => {
          const token = resp.data.token
          const user = resp.data.user
          localStorage.setItem('token', token)
          axios.defaults.headers.common['Authorization'] = token
          commit('auth_success', token, user)
          resolve(resp)
        })
        .catch(err => {
          commit('auth_error')
          localStorage.removeItem('token')
          reject(err)
        })
    })
  }
}

Answer №1

require('axios')

It's best practice to include this in the actions.js file for easy access. Remember to import it individually per file or utilize global imports.

Answer №2

To make axios accessible globally in your application's main entry point (such as app.js), you can define it like this:

global.axios = require('axios')

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

Error: The term 'RequestCompleted' is not recognized by Microsoft JScript

Does anyone have any suggestions? The error above occurs when this code is executed: Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RequestCompleted); Specifically within this section: <script language="javascript" type="text/javas ...

Conditionally displaying ng-options in AngularJSI'm looking for a

After spending hours searching, I'm unable to find a solution to my problem. I was able to implement it before but lost the code and can't remember how I did it. I need to display only certain array values in a select box using ng-options. The d ...

How to properly display date format in Node.js when using EJS templates with MySQL

When retrieving dates from the database, I am looking to break them down into two separate numbers. 7:00-8:00 //array[0]=7:00 and array[1]=8:00 9:00-9:30 14:30-15:00 Below is my code, but it is returning NaN NaN: <% time_slots.forEach((timeslot ...

Searching DynamoDB in node.js using mapped items

In my DynamoDB table, I am trying to retrieve all Items where the Review.ID matches 123. Item: { id: 1, review: { Id: 123, step1: 456, step2: 789, step3: 1234, }, // Add more items here }, Item: { id: 2, review: { Id: 123 ...

Using jQuery to locate and delete multiple attributes from div elements

My goal is to locate all div elements with the class name "comment-like" that also have data-id attributes set to 118603,1234,1234,118601,118597. If a div contains any of these data values, then I want to remove that data attribute. I've attempted th ...

Unable to execute app.get in Express framework of Node.js

const express = require('express'); let router = express.Router(); router.get('/create-new', (req, res, next) => { res.send('<form action="/submit-data" method="POST"><input type="text" name="name"><button ...

The computed property in Vue JS is providing an unexpected output

I need assistance with a task in Vue JS that I'm struggling with. I can't seem to figure out what's causing the issue in this code. The task involves creating a dynamic table with 5 columns, each with a background color of red, blue, yellow ...

Developing a Node.js system for mapping ids to sockets and back again

Managing multiple socket connections in my application is proving to be a challenge. The app functions as an HTTP server that receives posts and forwards them to a socket. When clients establish a socket connection, they send a connect message with an ID: ...

Often, while working on Vue.js projects in VS Code, the code syntax highlighting can become chaotic

Displayed below is the issue: I am finding it difficult to comprehend why, even though the syntax and format appear to be correct, it is all very confusing. I thoroughly review my code but I am unable to unravel the mystery. ...

What causes my backend to crash when incorrect credentials are entered?

Whenever I input incorrect credentials on my login page, it causes the backend to crash. I want to avoid this situation and prevent my backend from crashing. Can somebody please assist me in identifying and rectifying the mistake? I am using MongoDb as my ...

steps for including a JS file into Next.js pages

Is it possible to directly import the bootstrap.bundle.js file from the node_modules/bootstrap directory? import "bootstrap/dist/css/bootstrap.rtl.min.css"; function MyApp({ Component, pageProps }) { return ( <> <Script src="node_m ...

Using the `on` method of jQuery to make an Ajax request

I'm facing a challenge with using Jquery to load dynamic wall posts for followers. The issue arises when trying to work with dynamic content in the traditional click method. To solve this, I have implemented the on method for the response. However, I ...

Steps to retrieve the latest value of a specific cell within the Material UI Data Grid

After updating the cell within the data grid, I encountered an issue where I could retrieve the ID and field using the prop selectedCellParams, but retrieving the modified value was proving to be challenging. In order to successfully execute the PUT reque ...

Having trouble with the dropdown onclick event not triggering when an item is selected in React?

I am having an issue where the onclick event handler is not being called when a dropdown item is selected. In my code, I am generating a dropdown inside a loop in the componentDidMount() lifecycle method. I am passing an event handler function named "show ...

I am looking to utilize the data from a POST request to dynamically update the DOM through a script.js file. How can

After sending a post request, I am looking to update my database and then use an array to dynamically update the HTML content. However, I am struggling with how to pass this data to my script.js file. Here is my progress so far: SERVER let expenseAmo ...

How to display a minimalist white dot in three.js

I am currently working with THREE.WebGLRenderer and I have a requirement to display multiple white dots of the same size at specific locations in 3D space. Is it recommended to use sprites, calculate the 2D screen coordinates, and utilize SpriteMaterial w ...

New methods for Sequelize ES6 models do not currently exist

Encountering issues while using Sequelize JS v4 with ES6 classes, I'm facing difficulty with the execution of instance methods. Despite being defined in the code, these methods appear to be non-existent. For instance - Model File 'use strict&a ...

Dynamically extract key values from JSON data and display them on an HTML page with checkboxes for selection. Generate a new JSON object containing

I am facing the challenge of parsing an unknown JSON with uncertain key-value pairs. As I do not have prior knowledge of the keys to access, my goal is to traverse through every key in the JSON and display all keys and their corresponding values on the scr ...

CSS or jQuery: Which is Better for Hiding/Showing a Div Within Another Div?

Show only class-A at the top of the page while hiding all other classes (x,x,c). Hide only class-A while showing all other classes (x,x,c). Is it possible to achieve this? <div class="x"> <div class="y"> <div class="z"&g ...

Error: Unable to locate the module: Vue-Picture-BD-Marker

After successfully building my Vue project on my personal MacBook and running npm build without any issues, I encountered a problem when trying to deploy it on my CentOS server using Jenkins. The build failed with the following log: ERROR in ./node_modules ...