首页 > 解决方案 > Laravel vue axios post没有数据作为json响应返回

问题描述

我创建了一个简单的系统来评论帖子或视频。一切正常。
一个名为loadComments()的函数显示与帖子或视频相关的评论。
当用户提交新评论时,会创建评论,但为了查看新评论,我必须刷新页面,因为我收到未定义的响应。

这里是控制器中的存储功能

    public function store(Request $request)
{

        $comments = Comment::create([
        'comment' => $request->comment,
        'user_id' => auth()->user()->id,
        'post_id' => $request->post_id
    ]);


    return response()->json([
        'comments' => $comments,
        'success' => 'Comment created successfully!'
    ],200);

}

这里的 addComment 方法:

  addNewComment() {

            const formData = {
                comment: this.comment,
                post_id: this.propsVideoid
            }

            axios
                .post(this.commentsUri, formData)
                .then(response => {
                    this.comments.unshift(response.data.comments)
                })
                .catch(error => {
                    this.errors = [];
                    if(error.response.status == 422) {
                        this.errors = error.response.data.errors;
                    }
                })

        },

这里加载和添加方法一起

       addNewComment() {

            const formData = {
                comment: this.comment,
                post_id: this.propsVideoid
            }

            axios
                .post(this.commentsUri, formData)
                .then(response => {
                    this.comments.unshift(response.data.comments)
                })
                .catch(error => {
                    this.errors = [];
                    if(error.response.status == 422) {
                        this.errors = error.response.data.errors;
                    }
                })

        },
        loadComments() {
            axios.get(this.commentsListUri, {
                params: {
                    post_id: this.propsVideoid
                }
            }).then(response => {
                this.comments = response.data.comments;
            });
        },
    },
    mounted() {

        this.loadComments();

    }

addNewComment ()方法在数据库中插入新评论,但它不返回任何 json 响应。

标签: laravelvue.js

解决方案


推荐阅读