我目前正在使用Laravel@5.5与Redis,laravel-echo-server和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(未经授权)
未知(承诺) 错误:请求失败,状态码为401
我做了很多尝试和研究,即使是Laravel Passport,也没看到我被困在哪里。
亲切的问候,
JeuneApprenti。
答案 0 :(得分:2)
如果有人真的需要答案,我终于使用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>