POST 使用 Laravel 5.5 的 Axios 请求

POST Axios request using Laravel 5.5

我目前正在使用 Laravel@5.5 with Redis, laravel-echo-server and Axios 并尝试制作实时聊天功能。
我没有使用 vue.js 作为前端框架。

我在使用 axios 和 jquery 发出 POST 请求时遇到了一些问题,这个:

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

输出这个:

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

我做了很多尝试和研究,即使是 Laravel Passport,也看不出我卡在哪里。

亲切的问候,
JeuneApprenti.

万一有人真的需要那里的答案,我最终将 axios 切换为简单的 fetch 方法并设置了 socket.io-client

看起来像这样:

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

然后,您可以在您的视图中调用此脚本,通过 socket.io 从 websockets 获取数据:

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