【发布时间】: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">×</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') },