Search code examples
laravelredisaxiosphp-7laravel-echo

POST Axios request using Laravel 5.5


I'm currently using Laravel@5.5 with Redis, laravel-echo-server and Axios and trying to make a realtime chat feature.
I'm not using vue.js as frontend framework.

I'm having some problems when make a POST request using axios and jquery, this :

-> echo.js 
 $('#submit').click(function() {
 var content = $('#content').val();    
 axios.post('/api/conversation/update', {   
 content: content });  
});


-> api.php
    Route::post('/conversation/update', 'ConversationController@update');


-> bootstrap.js
   /**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';


/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

Output this :

POST http://localhost:8000/api/conversation/update 401 (Unauthorized)
Uncaught (in promise) Error: Request failed with status code 401

I've make many try and research, even with Laravel Passport, and don't see where i'm stuck.

Kind regards,
JeuneApprenti.


Solution

  • In case someone really need an answer there, I finally switched using axios for simple fetch method and set up a socket.io-client

    It looks like this :

    -> echo.js   
    const fetchApi = async function (url, options = {}) {
      let response = await fetch(url, {
        credentials: 'same-origin',
        headers: {
          'X-Requested-With': 'XMLHttpRequest',
          'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
          'Acccept': 'application/json',
          'Content-Type': 'application/json',
          'X-Socket-ID': Echo.socketId(),
        },
        ...options
      })
      if (response.ok) {
        return response.json()
      } else {
        throw await response.json()
      }
    }
    
    -> api.php
    
    Route::group(['middleware' => ['auth:api']], function () {
      Route::get('/conversations', 'Api\ConversationController@index');
      Route::get('/conversations/{user}', 'Api\ConversationController@show')   
       ->middleware('can:talkTo,user');
      Route::post('/conversations/{user}', 'Api\ConversationController@store') 
       ->middleware('can:talkTo,user');
    });
    
    -> bootstrap.js
    
    import Echo from 'laravel-echo'
    
    window.Echo = new Echo({
      broadcaster: 'socket.io',
      host: window.location.hostname + ':6001',
    });
    window.io = require('socket.io-client');
    

    Then, you can call this script in your views to get datas from websockets via socket.io :

    <script src="//{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>