分派的操作会自动返回 html 响应,但手动运行时会返回 JSON 响应

问题描述 投票:0回答:1

我有一个名为

fetchUserPermissions
的操作,它通过 axios 从 api 端点返回权限集。此操作通过另一个名为 init 的操作运行,该操作通过实用程序
dispatchActionForAllModules
自动运行,该实用程序基本上在所有模块/子模块中查找 init 操作并运行它。这部分似乎工作正常,但端点似乎返回 html (?) 而不是 JSON 响应。返回的响应类似于:

<!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>

重要的是要知道我使用

webpack_loader
包通过 Django 运行 Vue。上面的html就是为Vue服务的index.html。

但是,当我在组件的

created()
钩子中分派操作时,它会按预期工作,并返回类似
{ "id": 1, "is_staff": true, "is_superuser": true, "permissions": [ "view_user" ], "group_permissions": [ "has_users_export" ] }
的内容。

dispatchActionForAllModules
实用程序基本上是从 vue-enterprise-bolierplate 存储库复制粘贴。

我如何确保它按预期返回 JSON 响应?

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')

状态/模块/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

状态/模块/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)
  }
}

组件中的计算属性直接从store获取数据,如:

permissions() {
  return this.$store.state.users.requestUserPermissions
}
javascript vue.js vuex
1个回答
0
投票

我遇到了同样的问题,我在使用时收到 html 响应 等待 axios.get('url'),当我将其更改为时,它开始像魔术一样工作 等待这个。$axios.get('url')

© www.soinside.com 2019 - 2024. All rights reserved.