When a function is triggered automatically, it sends back an HTML response by default, whereas executing it manually will yield

My current setup involves an action named fetchUserPermissions that retrieves a permission set from an api endpoint using axios. This action is triggered by another action called init, which is automatically executed through the utility dispatchActionForAllModules. This utility searches for the init action in all modules/submodules and executes it. Although this mechanism seems to be functioning correctly, the issue arises when the api endpoint returns HTML instead of the expected JSON response. The returned HTML content looks something like this:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Title</title> </head> <body> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <script type="text/javascript" src="http://0.0.0.0:8080/bundle.js" ></script> </body> </html>

It's worth noting that I am using Vue with Django through the webpack_loader package. The HTML content mentioned above is the index.html file that serves the Vue application.

Interestingly, when I dispatch the action within the created() hook of a component, it works as expected and returns a JSON response like this:

{ "id": 1, "is_staff": true, "is_superuser": true, "permissions": [ "view_user" ], "group_permissions": [ "has_users_export" ] }
.

The dispatchActionForAllModules utility is essentially copied from the vue-enterprise-bolierplate repository.

How can I ensure that the endpoint returns the JSON response as expected?

state/store.js

import Vue from 'vue'
import Vuex from 'vuex'

import dispatchActionForAllModules from '@/utils/dispatch-action-for-all-modules'
import modules from './modules'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules,
  strict: process.env.NODE_ENV !== 'production',
})

export default store

// automatically run the `init` action for every module,
// if one exists.
dispatchActionForAllModules('init')

state/modules/index.js

import camelCase from 'lodash/camelCase'

const modulesCache = {}
const storeData = { modules: {} }

;(function updateModules() {
  const requireModule = require.context(
    // Search for files in the current directory.
    '.',
    // Search for files in subdirectories.
    true,
    // Include any .js files that are not this file or a unit test.
    /^((?!index|\.unit\.).)*\.js$/
  )

  // For every Vuex module...
  requireModule.keys().forEach((fileName) => {
    const moduleDefinition =
      requireModule(fileName).default || requireModule(fileName)

    // Skip the module during hot reload if it refers to the
    // same module definition as the one we have cached.
    if (modulesCache[fileName] === moduleDefinition) return

    // Update the module cache, for efficient hot reloading.
    modulesCache[fileName] = moduleDefinition

    // Get the module path as an array.
    const modulePath = fileName
      // Remove the "./" from the beginning.
      .replace(/^\.\//, '')
      // Remove the file extension from the end.
      .replace(/\.\w+$/, '')
      // Split nested modules into an array path.
      .split(/\//)
      // camelCase all module namespaces and names.
      .map(camelCase)

    // Get the modules object for the current path.
    const { modules } = getNamespace(storeData, modulePath)

    // Add the module to our modules object.
    modules[modulePath.pop()] = {
      // Modules are namespaced by default.
      namespaced: true,
      ...moduleDefinition,
    }
  })

  // If the environment supports hot reloading...
  if (module.hot) {
    // Whenever any Vuex module is updated...
    module.hot.accept(requireModule.id, () => {
      // Update `storeData.modules` with the latest definitions.
      updateModules()
      // Trigger a hot update in the store.
      require('../store').default.hotUpdate({ modules: storeData.modules })
    })
  }
})()

// Recursively get the namespace of a Vuex module, even if nested.
function getNamespace(subtree, path) {
  if (path.length === 1) return subtree

  const namespace = path.shift()
  subtree.modules[namespace] = {
    modules: {},
    namespaced: true,
    ...subtree.modules[namespace],
  }
  return getNamespace(subtree.modules[namespace], path)
}

export default storeData.modules

state/modules/users.js

import axios from 'axios'

export const state = {
  requestUserPermissions: [],
}

export const mutations = {
  'FETCH_USER_PERMISSIONS' (state, permissions) {
    state.requestUserPermissions = permissions
  },
}

export const actions = {
  init: ({ dispatch }) => {
    dispatch('fetchUserPermissions')
  },
  fetchUserPermissions: ({ commit }) => {

    axios.get('user/permissions/').then(result => {
      console.log(result.data)
      commit('FETCH_USER_PERMISSIONS', result.data)
    }).catch(error => {
      throw new Error(`API ${error}`)
    })
  },
}

utils/dispatch-action-for-all.modules.js

import allModules from '@/state/modules'
import store from '@/state/store'

export default function dispatchActionForAllModules(actionName, { modules = allModules, modulePrefix = '', flags = {} } = {}) {
  // for every module

  for (const moduleName in modules) {
    const moduleDefinition = modules[moduleName]

    // if the action is defined on the module
    if (moduleDefinition.actions && moduleDefinition.actions[actionName]) {
      // dispatch the action if the module is namespaced, if not
      // set a flag to dispatch action globally at the end
      if (moduleDefinition.namespaced) {
        store.dispatch(`${modulePrefix}${moduleName}/${actionName}`)
      } else {
        flags.dispatchGlobal = true
      }
    }

    // if there are nested submodules
    if (moduleDefinition.modules) {
      // also dispatch action for these sub-modules
      dispatchActionForAllModules(actionName, {
        modules: moduleDefinition.modules,
        modulePrefix: modulePrefix + moduleName + '/',
        flags,
      })
    }
  }

  // if this is at the root ant at least one non-namespaced module
  // was found with the action
  if (!modulePrefix && flags.dispatchGlobal) {
    // dispatch action globally
    store.dispatch(actionName)
  }
}

The computed property in the component retrieves the data from the store directly, like this:

permissions() {
  return this.$store.state.users.requestUserPermissions
}

Answer №1

Encountering a similar issue, I found that I was receiving an HTML response while utilizing the code 'await axios.get('url')'. After making the adjustment to 'await this.$axios.get('url')', I successfully obtained the accurate response.

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

Ways to prevent onMouseDown from triggering when the element is exclusively clicked?

I'm currently working on developing a game where units (svg elements) are controlled using React. In this game, the units should be draggable, and clicking on a unit should open a form. However, when I click on the unit, only the mousedown event is t ...

How can I extract unique dates from my database in Laravel and display them without duplicates?

Currently, I am actively involved in a Laravel Jetstream Project that utilizes Inertia.js. This particular project is focused on displaying the GPS history of cars tracked using a tracker and then plotting them on a map to visualize the complete geo-histo ...

Is sending an AJAX request to a Node.js Express application possible?

Currently, I am attempting to authenticate before utilizing ajax to add data into a database $('#button').click(function () { $.post('/db/', { stuff: { "foo" : "bar"} }, callback, "json"); }); Below is my node.js code: ...

Automatically showcase images from a directory upon webpage loading

Is there a way to modify my code so that the images from the first directory are displayed on the page when it loads, instead of waiting for a menu option to be clicked? The page looks empty until a menu option is selected, and I would like the images to s ...

A Simple Guide to Setting a Background Image in React Native with the Nativebase.io Library

What is the process for including a background image in React Native with the help of the Nativebase.io Library? I have a specific screen where I need to incorporate a background image, with all other elements positioned at the center of the image. ...

Adjusting the height of a GAS iframe in WordPress with iframe-resizer: A step-by-step guide

I would like to embed an iframe of my Google Application Script Web into my WordPress site without the scroll bar. Refer to the image below for context. https://i.stack.imgur.com/7L6Tw.png I encountered an error message while attempting to use the iframe ...

When a single object is entered, JSON returns 'undefined', however, it works successfully when using the .map() function

Utilizing Axios to fetch data from DeezerAPI, I initially rendered information using .map() and everything worked smoothly when passing it to a Component. However, when attempting to access a single JSON object, I encountered an 'undefined' error ...

Utilize dynamic global variables in React that are provided during runtime, making them unpredictable during the build process

I am currently developing an application for Overwolf, which you can find more information about at For this platform, applications are built using html/js and run in the Overwolf Browser. The browser provides access to the Overwolf API through a global v ...

Is the JSON parsing issue being caused by Bodyparser?

I am encountering an issue with parsing JSON on my server using the body-parser NPM module and Express. The JSON data is not appearing correctly on the server for some reason. Here is a snippet of my server code: ... app.use(bodyParser.json()); app.use(bo ...

JavaScript - Matching overlapping time intervals

Struggling to develop a custom filter using Javascript, I aim to determine if two time ranges in millisecond getTime() format match. The first time range is retrieved from an object while the second comes from user input for filtering. Currently, my code c ...

Is there a way to fetch a random record from a MongoDb collection and exhibit all the fields of that haphazardly chosen document in HTML?

In my current project, I am fetching a random document from a MongoDB Collection and attempting to showcase all the fields of that document in HTML. Although I can successfully retrieve a random document, the issue arises when trying to display its fields ...

Inject an HTML or jade webpage into a div within another HTML or jade webpage

I'm facing an issue in my Node.js project with a script (JS) that is responsible for loading a Jade page into a div of another Jade page using $("#div").load(directory). Despite specifying the directory of the jade page to be loaded, I keep getting an ...

Utilizing document.write() for displaying markup content

I have an inline SVG stored as a variable on my webpage and I am making some changes to it. How can I display viewText on the page (not the SVG image) with the modifications? What is the best way to make viewText appear on the page? For instance: ...

Issue with Accordion Panel Content Scroll Bar

Hello there, I've encountered a puzzling problem with my website. My objective is to insert a Time.ly Calendar widget into one panel of my accordion. On this page, "TOURNAMENTS: , the widget appears exactly as desired. However, when I replicate the c ...

Issues encountered when trying to use default color classes in Tailwind CSS

I'm currently working on a React project that utilizes the Tailwind CSS Framework. To integrate Tailwind into my React app, I used NPM to install it in the following way: npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p After i ...

Transform **kerry James O'keeffe-martin** into **Kerry James O'Keeffe-Martin** using TypeScript and Java Script

Is there a way to capitalize names in both TypeScript and JavaScript? For example, changing kerry James O'keeffe-martin to Kerry James O'Keeffe-Martin. ...

Requesting JSON data from an API with cross-origin - "You might require a suitable loader to manage this particular file format."

I am currently attempting to retrieve JSON data from the Genius API using Webpack and Axios in a web browser. This involves a Cross-Origin Request, which can sometimes be a bit challenging. Initially, I encountered the following error message: Failed to ...

Using JQuery to handle click events on an array of checkboxes and displaying the value of the selected

I am struggling to show the label text and checkbox value from a checkbox array whenever each one is clicked (for testing purposes, assume I want it to appear in an alert). My HTML looks like this: <label class="checkbox"> <input type="checkbox" ...

An issue has arisen with loading chunks in Ionic 5/Angular, possibly due to an un

I am currently working on enhancing the offline capabilities of my Ionic 5 app. To achieve this, I have implemented a strategy where data is stored in SQLite while the app is connected, and then retrieved from SQLite when offline instead of making HTTP req ...

What is the best way to enforce a required bindings property in an AngularJS component?

Suppose I have the following component defined: angular.module('myApp').component('myComponent', { templateUrl: 'myComponent.html', bindings: { myPropOne: '<', myPropTwo: '<' ...