【问题标题】:how to insert data to database with vue and laravel如何使用 vue 和 laravel 将数据插入数据库
【发布时间】:2023-03-27 18:00:01
【问题描述】:

我尝试使用 vue js 和 laravel 创建一个 crud 系统。

我已经创建了 api 路由等等...

但是当我点击提交时,我收到了消息405 (Method Not Allowed)

这是我的AddArtist.vue 文件

<form @submit.prevent="add">
<input type="text" class="form-control" v-model="artist.name"  placeholder="Artist Name">
<button class="btn btn-success" type="submit">Save</button>
</form>

<script>
    export default {
        data: function () {
        return {
            errors: [],
            image: '',
            artist: {
                    name: '',
                }
        }
        },
        methods: {
            add() {
                axios.post('/api/artist/store-artist', this.$data.artist)
                    .then((response) => {
                        alert('Success add Artist')
                        console.log(response)
                    })
            },
        },
            mounted() {
                console.log('Add Artist Mounted.')
            }
    }
</script>

还有我的api.php路线

Route::group(['middleware' => 'cors'], function(){
    Route::post('addartist/store-artist', 'ArtistController@store');
});

这里是我的控制器ArtistController.php

public function store(Request $request)
    {
        $input = $request->all();
        dd($input);
    }

最后一个是我的模特Artist.php

class Artist extends Model
{
    protected $table = 'artist';
    protected $fillable = ['artist_name', 'date_birth', 'cover', 'gender'];
}

【问题讨论】:

  • 在axios hrader中添加csrf token
  • 这是……?
  • @DhruvRaval if (token) { window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content; } else { console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token'); } 已经在 boostrap.js 中设置了

标签: laravel laravel-5 vue.js routes vue-router


【解决方案1】:

这是拼写错误:

在路由中将addartist/store-artist 更改为artist/store-artist

你的 api 是:

Route::group(['middleware' => 'cors'], function(){
    Route::post('addartist/store-artist', 'ArtistController@store');
});

你正在做:

axios.post('/api/artist/store-artist', this.$data.artist)
                    .then((response) => {
                        alert('Success add Artist')
                        console.log(response)
                    })

【讨论】:

  • 还是不行,我得到405 (Method Not Allowed)Error: Request failed with status code 405
  • 可能的解决方案 1) 从此路由中删除中间件 2) 运行 php artisan route:list 你将获得应用程序检查路由 url 的所有路由。
  • 是否需要从 store 方法中删除 dd
猜你喜欢
  • 2023-01-18
  • 2018-08-06
  • 1970-01-01
  • 2020-07-05
  • 2014-04-11
  • 2020-03-31
  • 2019-09-26
  • 2018-01-31
  • 2017-12-20
相关资源
最近更新 更多