Search code examples
javascriptphpjqueryvue.jslaravel-5.3

Laravel AJAX Request into route api Vue error


I am trying to make an ajax request using Vue to get data from an API route using the auth middleware to get recently created issues. I was able to get it to work without checking auth however i need it to check auth and also get the Users id that is creating the request. I currently have this. My view:

<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>

My api.php route:

<?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();
  });
});

My messages.js vue script:

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'
});

The error message i get currently is 401 and the route is giving back : {"error":"Unauthenticated."}


Solution

  • You have written:

    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    

    This looks for a <meta> element, whose name is csrf-token, and parses out the content. So, for it to work, you need to add that meta tag to the document head. Try this:

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