我正在尝试使用Vue使用auth中间件从API路由获取数据来获取ajax请求,以获取最近创建的问题。我能够在不检查身份验证的情况下让它工作,但我需要它来检查身份验证并获取创建请求的用户ID。我现在有这个。 我的观点:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
<script src="/public/js/adminApp.js"></script>
<template id="messages-template">
<div>
<ul class="menu" v-for="messages in list">
<li><!-- start message -->
<a href="#">
<div class="pull-left" style="margin-left: 9px;margin-right: 9px;">
<i class="fa fa-pencil"></i>
</div>
<h4>@{{ messages && messages.name }}
<small><i class="fa fa-clock-o"></i> 5 mins</small>
</h4>
</a>
</li>
</div>
</div>
</template>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script type="text/javascript" src="/public/js/messages.js">
</script>
我的api.php路线:
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group(['middleware' => ['auth:api']], function () {
Route::get('/test', function (Request $request) {
return App\issue::latest()->get();
});
});
我的messages.js vue脚本:
Vue.component('messages', {
template: '#messages-template',
data: function (){
return {
list:[]
};},
created (){
$.getJSON('/api/test', function(messages){
this.list = messages;
}.bind(this))
}
});
new Vue({
el: '#messagesArea'
});
我目前收到的错误消息是401,路线正在回馈:{"error":"Unauthenticated."}
答案 0 :(得分:0)
你写过:
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
这会查找<meta>
元素,其名称为csrf-token
,并解析content
。因此,要使其正常工作,您需要将meta
标记添加到文档头。试试这个:
<meta id="token" name="csrf-token" content="{{ csrf_token() }}">