我正在尝试使用 Laravel 5.4 + Redis + Sockets + Echo 设置事件广播,但我遇到了问题。我跑过:
npm install --save laravel-echo
我将以下内容放在资源/资产/js/bootstrap.js 文件的底部:
import Echo from "laravel-echo"
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
然后我运行以下命令来编译所有内容:
npm run dev
我将编译后的 app.js 文件包含在头部并尝试像这样听:
<!DOCTYPE html>
<html lang=en>
<head>
<meta name="csrf-token" content="epkZXByjsW4lU6wwD2mELWe60Q26m3642lvMCoLK">
<script src="http://localhost:3000/js/app.js"></script>
</head>
<body>
<h1>Chat</h1>
<script src="//localhost:6001/socket.io/socket.io.js"></script>
<script type="text/javascript">
Echo.private('chat')
.listen('MessageSentEvent', (e) => {
console.log(e.update);
});
</script>
</body>
</html>
在控制台中,我收到以下两个错误:
Uncaught TypeError: Cannot read property 'csrfToken' of undefined
at Object.<anonymous> (bootstrap.js:24)
at __webpack_require__ (bootstrap 2b5c37a…:19)
at Object.<anonymous> (app.js:8)
at __webpack_require__ (bootstrap 2b5c37a…:19)
at Object.<anonymous> (module.js:22)
at __webpack_require__ (bootstrap 2b5c37a…:19)
at bootstrap 2b5c37a…:65
at bootstrap 2b5c37a…:65
(anonymous) @ bootstrap.js:24
__webpack_require__ @ bootstrap 2b5c37a…:19
(anonymous) @ app.js:8
__webpack_require__ @ bootstrap 2b5c37a…:19
(anonymous) @ module.js:22
__webpack_require__ @ bootstrap 2b5c37a…:19
(anonymous) @ bootstrap 2b5c37a…:65
(anonymous) @ bootstrap 2b5c37a…:65
chat:36 Uncaught ReferenceError: Echo is not defined
at chat:36
我究竟做错了什么?