axios.post得到500错误

时间:2017-04-28 12:58:26

标签: laravel vuejs2 axios

我试图用laravel 5.4和vue 2.0创建一个网站聊天应用 我遵循了这个教程https://www.youtube.com/watch?v=8aTfMHg3V1Q,一切正常,直到我尝试使用axios.post持久发送消息

我的web.php:

Route::group(['prefix' => 'profile/{username}/you'], function()
{
Route::post('/privatechat/{id}', function(){
        $user = Auth::user();

        $user->send()->create([
            'chat_room'     =>  request()->segment(5),
            'message'       =>  request()->get('message'),
            'sender_id'     =>  Auth::user()->id,
            'receiver_id'   =>  request()->input('receiver')
        ]);

        return ['status' => 'OK'];
    })->middleware('auth');
 });

我的观点:

var url = location.href + '/' + $(this).val();
const app = new Vue({
                el: '#app',
                data: {
                    messages: [],
                    sendClass: 'chat-send'
                    //Điều kiện
                },
                methods: {
                    addMessage(message) {
                        this.messages.push(message);

                        axios.post(url, message)
                        .then(function (response) {
                            alert('Complete! Thanks for your message!');
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                    }
                },
                mounted() {
                    var u = url;
                    axios.get(u).then(response => {
                        //console.log(response);
                        this.messages = response.data;
                    });
                }
            });

当我按Enter键发送消息时,此错误会显示在chrome控制台中:

POST 500 (Internal Server Error)
dispatchXhrRequest @ app.js:11154
xhrAdapter @ app.js:10991
dispatchRequest @ app.js:11633

我的代码在哪里错了?

2 个答案:

答案 0 :(得分:0)

我使用laravel-log-viewer看到:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'PRIMARY' 
in /home/vagrant/website/hgc/vendor/laravel/framework/src/Illuminate/Database/Connection.php:449

答案 1 :(得分:0)

你正在创建新的聊天(新条目),如果我没有错,你可以不用发送方法吗? Just Chat :: create ...因为您首先检索已有ID的聊天,然后插入与已使用的ID相同的聊天无法正常工作。