【发布时间】:2018-10-11 10:28:07
【问题描述】:
我在尝试用axios 发表新评论时收到'unauthorized' 错误 ..... 我在@987654325 中的axios.post 之前添加了(console.log(this.user.api_token);) @ 方法 。输出是:"undefined" !!!!!!!!!!
我正在学习,我对api的了解不多。但我不认为用户api_token 是手动设置的。还是它???
脚本:
<script>
const app = new Vue({
el: '#app',
data: {
comments: {},
commentBox: '',
post: {!! $post->toJson() !!},
user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!}
},
mounted() {
this.getComments();
},
methods: {
getComments() {
axios.get('/api/post/'+this.post.id)
.then((response) => {
this.comments = response.data
})
.catch(function (error) {
console.log(error);
});
},
postComment() {
console.log(this.user.api_token);
axios.post('/api/post/'+this.post.id , {
api_token: this.user.api_token,
body: this.commentBox
})
.then((response) => {
this.comments.unshift(response.data);
this.commentBox = '';
})
.catch((error) => {
console.log(error);
})
}
}
})
api 路由
Route::get('/post/{post}', 'CommentController@index');
Route::middleware('auth:api')->group(function () {
Route::post('/post/{post}', 'CommentController@store');
});
评论控制器
public function index(Post $post){
return response()->json($post->comments()->with('user')->get());
}
public function store(Request $req,Post $post){
$comment=$post->comment()->create([
'user_id'=>auth::id(),
'body'=>$req->body
]);
$comment=Comment::where('id',$comment->id)->with('user')->first();
return $comment->toJson;
}
【问题讨论】:
标签: json laravel vue.js token axios