【问题标题】:Laravel API: "POST http://localhost/api/post 419 (unknown status)" (Vue.js)Laravel API:“POST http://localhost/api/post 419(未知状态)”(Vue.js)
【发布时间】:2021-06-21 06:21:09
【问题描述】:

我正在尝试使用 Laravel Api 在 vue 组件中发帖。

我在welcome.blade.php 中获得了CSRF 令牌:

<meta name="csrf-token" content="{{ csrf_token() }}">

当我单击按钮时,页面不会刷新或添加任何内容。 如果我点击按钮,我会在我的控制台中得到这个:

POST http://localhost/api/post 419(未知状态)


PostList.vue

<template>
    <div class="container py-4">
        <form enctype="multipart/form-data" method="post" action="" @submit.prevent="addPost">
            <input type="hidden" name="_token" value=""/>
            <div class="modal-header">
                <h4 class="modal-title">Create Post</h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>Title</label>
                    <input type="text" class="form-control" placeholder="Title" v-model="post.title">
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea class="form-control" placeholder="Body" v-model="post.body"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
                <input type="submit" class="btn btn-primary" value="Add">
            </div>
        </form>
    </div>
</template>


<script>
    export default {
        data() {
            return {
                post: {
                    id: '',
                    title: '',
                    body: ''
                }
            };
        },
        created() {
            this.getPosts();
        },
        methods: {
            addPost(){
                fetch('api/post', {
                    method: 'post',
                    body: JSON.stringify(this.post),
                    headers: {
                        'content-type': 'apllication/json'
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        this.getPosts();
                    })
                    .catch(err => console.log(err));
            }
        }
    };
</script>

PostController.php

public function store_vue(Request $request){
        $post = new Posts();
        $post->title = $request->get('title');
        $post->body = $request->get('body');
        $post->slug = Str::slug($post->title);

        $post->author_id = $request->user()->id;

        if ($post->save()) {
            return new PostResource($post);
        }
    }

【问题讨论】:

  • 我认为你在API路由中没有任何身份验证,但你可以使用 laravel sanctum 进行身份验证
  • @Orhan 哦,好吧,所以它无法读取登录用户。我正在使用身份验证。你能解释一下我如何将身份验证放在 api 路由中吗?
  • 将此添加到您的headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },

标签: laravel vue.js


【解决方案1】:

您收到 419 错误,因为请求缺少 CSRF 令牌。

您可以将其添加到您的表单中,看看它是否适合您

<form enctype="multipart/form-data" method="post" action="" @submit.prevent="addPost">
    <input type="hidden" name="_token" value="{{ csrf_token() }}" />

将带有 CSRF 的标头添加到您的通话中

<script>
    export default {
        data() {
            return {
                post: {
                    id: '',
                    title: '',
                    body: ''
                }
            };
        },
        created() {
            this.getPosts();
        },
        methods: {
            addPost(){
                fetch('api/post', {
                    method: 'post',
                    body: JSON.stringify(this.post),
                    headers: {
                        'content-type': 'apllication/json',
                        'X-CSRF-TOKEN': document.querySelector("meta[property='csrf-token']").getAttribute("content");
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        this.getPosts();
                    })
                    .catch(err => console.log(err));
            }
        }
    };
</script>

【讨论】:

  • 好的,我已经这样做了:'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 但现在我遇到了不同的问题.当我单击按钮时,我得到: POST localhost/api/post 500 (Internal Server Error) SyntaxError: Unexpected token
  • @ChrisServ 这是另一个需要详细代码/调试日志的问题。它主要发生在 json_decode()。尝试在解码之前转储输入。
  • @ChrisServ 一旦你修复了 500 错误(检查网络选项卡),那么你的 JSON 问题就会消失。
【解决方案2】:

Laravel 有一个名为 VerifyCsrfToken 的中间件,默认启用。它确保所有 POST 请求都有一个 csrf 令牌。此令牌确保请求仅来自我们的应用程序,而不是来自任何第三方 scraper 或表单提交工具。

当控制器在请求中没有得到_token时,它会抛出错误。
添加此'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 在像belwo一样的标题部分 你可以试试这个

 <script>
        export default {
            data() {
                return {
                    post: {
                        id: '',
                        title: '',
                        body: ''
                    }
                };
            },
            created() {
                this.getPosts();
            },
            methods: {
                addPost(){
                    fetch('api/post', {
                        method: 'post',
                        body: JSON.stringify(this.post),
                        headers: {
                            'content-type': 'apllication/json', 
                             'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    })
                        .then(response => response.text())
                        .then(data => {
                            this.getPosts();
                        })
                        .catch(err => console.log(err));
                }
            }
        };
    </script>

【讨论】:

  • 好的,我已经这样做了:'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 但现在我遇到了不同的问题.当我单击按钮时,我得到: POST localhost/api/post 500 (Internal Server Error) SyntaxError: Unexpected token
  • 评论这个.then(response =&gt; response.json())它会解决问题并使用这个.then(response =&gt; response .text()) 我会更新答案
  • 是的,这修复了 json 错误,谢谢。但我仍然有 500 错误
  • 你能把完整的错误贴出来吗
猜你喜欢
  • 2021-06-11
  • 2018-08-24
  • 2018-09-20
  • 2020-09-18
  • 1970-01-01
  • 2019-07-16
  • 2018-05-26
  • 2018-02-25
  • 2019-11-21
相关资源
最近更新 更多