首页 > 解决方案 > Laravel 中的 Vue 表单组件在提交时收到 422 错误

问题描述

我正在尝试将一个 Vue 表单组件添加到我的 Laravel 应用程序中,这样我就可以在整个应用程序的几个地方重用它。但是当我提交表单时,我收到一个 422 错误,说找不到路由。

表单组件:

<template>
<form @submit.prevent="mail" method="POST">

</form>
</template>
<script>
import FormMixin from '../FormMixin';

export default {
  mixins: [ FormMixin ],
  data() {
    return {
      'action': 'submit',
    }
  }
}
</script>

表单混合

export default {
  data() {
    return {
      fields: {},
      errors: {},
      success: false,
      loaded: true,
      action: '',
    }
  },

  methods: {

    mail() {
      if (this.loaded) {
        this.loaded = false;
        this.success = false;
        this.errors = {};
        axios.post(this.action, this.fields).then(response => {
          this.fields = {}; //Clear input fields.
          this.loaded = true;
          this.success = true;
        }).catch(error => {
          this.loaded = true;
          if (error.response.status === 422) {
            this.errors = error.response.data.errors || {};
          }
        });
      }
    },

  },
}

控制器

 public function mail(NewConctactRequest $contact) {
    	
    	Mail::to('example@example.com')->send(new NewContact($contact));

    	return redirect()->route('thank you');

    	return response()->json(null, 200);

    }

网络路由

Route::get('/home', 'HomeController@index')->name('home');
Route::get('adventures', 'PageController@adventures')->name('adventures');
Route::get('crew', 'PageController@crew')->name('crew');
Route::get('events', 'PageController@events')->name('events');
Route::get('gallery', 'PageController@gallery')->name('gallery');
Route::get('thank_you', 'PageController@thank_you')->name('thank you');
Route::get('contact', 'ContactController@show')->name('contact');
Route::post('submit', 'ContactController@mail')->name('mail contact');

我已经安装了 Axios,并且 CSRF 令牌设置在文档的头部。当我将表单用作标准表单(不使用 Vue)时,它会正确提交。

标签: laravelformsvue.jsvue-component

解决方案


推荐阅读