Vue.js中从Vuex Store发起Axios POST请求时出现500 HTTP错误
问题:Vuex中发起Axios POST请求返回500错误,组件中直接请求正常
在Vue.js项目中使用axios的POST方法向服务器提交数据时遇到问题:当请求从Vuex Store发起时会收到500 HTTP错误,但直接在组件中发起相同请求却一切正常。以下是相关代码实现:
组件代码
export default { name: 'addCategoury', data: () => ({ name: '', src: '', description: '', }), methods: { async AddCat() { const newCategory = { categoryName: this.name, description: this.description, imageUrl: this.src, } let result = await this.$store.dispatch('AddCategory', newCategory) if (result.data) { alert('shode'); } else { alert('result failed') } } } }
Vuex Store代码
import Vue from 'vue' import Vuex from 'vuex' import api from '../services/API' Vue.use(Vuex) export default new Vuex.Store({ state: { categories: [] }, getters: {}, mutations: { get_category(state, cat) { } }, actions: { async AddCategory(newCategory) { try { let result = await api().post('/category/create',newCategory); console.log(result) if (result.data) { alert('ok') return result } } catch (error){ return error } } }, })
API封装代码
import axios from 'axios' export default () => { return axios.create({ baseURL: 'https://limitless-lake-55070.herokuapp.com' }) }
组件模板代码
<template> <v-container class="align-text-center"> <v-form class="form"> <v-container> <v-row> <v-col cols="7"> <v-text-field outlined v-model="name" label="name" required> </v-text-field> </v-col> <v-col cols="7"> <v-text-field outlined v-model="src" label="image Source" required> </v-text-field> </v-col> <v-col cols="7"> <v-text-field outlined v-model="description" label="description"></v-text-field> </v-col> <v-col cols="12"> <v-btn @click="AddCat"> ADD </v-btn> </v-col> </v-row> </v-container> </v-form> </v-container> </template>
问题原因及解决方案
原因
Vuex的Action函数第一个参数固定是context上下文对象(包含state、commit、dispatch等属性),你当前的AddCategory函数直接把第一个参数当作传入的newCategory,导致实际传给后端的是context对象而非组件传递的分类数据,后端无法解析错误的数据格式,因此返回500服务器错误。
修正代码
修改Vuex Store中的AddCategory action,将第一个参数设为context,第二个参数才是实际的payload:
actions: { async AddCategory(context, newCategory) { // 新增context参数 try { let result = await api().post('/category/create', newCategory); console.log(result) if (result.data) { alert('ok') return result } } catch (error){ return error } } },
如果不需要使用context中的属性,也可以用下划线_占位:
async AddCategory(_, newCategory) { // ... 原有逻辑 }
修改后,传入的newCategory就是组件中传递的正确数据,请求即可正常被后端处理。
内容的提问来源于stack exchange,提问作者noosheen sh1995
相关产品推荐
相关产品推荐

