Laravel Echo 服务器在浏览器中没有响应
Laravel Echo server responds nothing in browser
我正在按照 https://medium.com/@dennissmink/laravel-echo-server-how-to-24d5778ece8b 中给出的教程进行操作。
我安装了 laravel-echo-server
、redis
、socket.io
、laravel-echo
。
这是laravel-echo-server init
的配置
{
"authHost": "http://localhost",
"authEndpoint": "/broadcasting/auth",
"clients": [],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": null,
"port": "6001",
"protocol": "http",
"socketio": {},
"secureOptions": 67108864,
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": false,
"allowOrigin": "",
"allowMethods": "",
"allowHeaders": ""
}
}
这段js代码在app.blade.php
的底部,所有页面都包含[=36=]
<script type="module">
import Echo from 'laravel-echo'
window.io = require('socket.io-client');window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
window.Echo.channel('test-event')
.listen('ExampleEvent', (e) => {
console.log(e);
});
</script>
我创建了一个事件php artisan make:event ExampleEvent
如下
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ExampleEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('test-event');
}
public function broadcastWith()
{
return [
'data' => 'Hi bro!'
];
}
}
和以下路线
Route::get('test-broadcast', function(){
broadcast(new \App\Events\ExampleEvent);
});
我还启动了一个队列监听器
php artisan queue:listen --tries=1
当我访问页面时 test-broadcast
我在终端中看到了这个
但是浏览器的控制台什么也没有显示,而 console.log(e);
必须 return 一些东西。我也是这样做的
window.Echo.channel('test-event')
.listen('ExampleEvent', (e) => {
alert('hi')
console.log(e);
});
但没有任何警报。听着好像有点问题
提前致谢。
更新
我在访问 login
或任何包含 app.blade.php
的页面时从浏览器控制台收到此错误
更新
我更新脚本代码如下
<script src="http://{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>
<script src="{{ asset('/js/app.js') }}"></script>
<script type="module">
import Echo from 'laravel-echo'
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
window.Echo.channel('test-event')
.listen('.ExampleEvent', (e) => {
console.log(e);
});
</script>
控制台仍然报错
TypeError: Error resolving module specifier: laravel-echo
更新
我运行
npm run development -- --watch
这是结果
cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
"--watch"
'cross-env' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/
setup/webpack.config.js "--watch"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Mamad\AppData\Roaming\npm-cache\_logs20-03-05T14_59_30_604Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ watch: `npm run development -- --watch`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ watch script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Mamad\AppData\Roaming\npm-cache\_logs20-03-05T14_59_30_697Z-debug.log
总的来说需要的是:
- 默认Laravel安装
- 作曲家要求predis/predis
- 安装 NPM 模块(laravel-echo-server,socket.io & laravel-echo)
通过控制台设置Laravel Echo Server(大部分为默认设置,域名除外):
{
"authHost": "http://echo",
"authEndpoint": "/broadcasting/auth",
"clients": [
{
"appId": "fc3de97a1787ea04",
"key": "ecf31edced85073f7dd77de1588db13b"
}
],
"database": "sqlite",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": null,
"port": "6001",
"protocol": "http",
"socketio": {},
"secureOptions": 67108864,
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": true,
"allowOrigin": "http://echo:80",
"allowMethods": "GET, POST",
"allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
}
}
设置 Redis 服务器并使用 Laravel broadcasting.php 文件连接到它
'default' => env('BROADCAST_DRIVER', 'redis')
或BROADCAST_DRIVER=.env文件中的redis
- 在web.php
中添加路由
Route::get('/test-broadcast', function(){
broadcast(new \App\Events\ExampleEvent);
return response('OK');
});
- 在bootstrap.js中添加代码:
import Echo from 'laravel-echo'
window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
已添加
window.Echo.channel('MyChannel')
.listen('.ExampleEvent', (e) => {
console.log(e);
});
- 运行
npm run dev
编译所有 Javascript 模块
- 运行
laravel-echo-server start
启动 Laravel Echo Server
- 运行
php artisan queue:listen --tries=1
启动监听队列
- 正在访问 http://echo/test-broadcast
已更新
11.1 将 ExampleEvent 的方法调整为:
public function broadcastOn()
{
return new Channel('MyChannel');
}
public function broadcastAs()
{
return 'ExampleEvent';
}
11.2 在welcome.blade.php中,在BODY标签前添加
<script type="text/javascript" src="/js/app.js"></script>
11.3 in database.php,设置redix前缀为空字符串值
'prefix' => env('REDIS_PREFIX', '')
不要忘记重新 运行 npm run dev
并清除浏览器缓存
结果
从你的错误来看,我认为你的包没有安装或导入不正确。您可以尝试安装包
npm install --save socket.io-client laravel-echo
将这些代码添加到 fileresources/js/bootstrap.js
的末尾
import Echo from "laravel-echo"
window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
和运行npm run watch
参考:https://laravel.com/docs/master/broadcasting#driver-prerequisites部分socket.io
我正在按照 https://medium.com/@dennissmink/laravel-echo-server-how-to-24d5778ece8b 中给出的教程进行操作。
我安装了 laravel-echo-server
、redis
、socket.io
、laravel-echo
。
这是laravel-echo-server init
{
"authHost": "http://localhost",
"authEndpoint": "/broadcasting/auth",
"clients": [],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true,
"host": null,
"port": "6001",
"protocol": "http",
"socketio": {},
"secureOptions": 67108864,
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": false,
"allowOrigin": "",
"allowMethods": "",
"allowHeaders": ""
}
}
这段js代码在app.blade.php
的底部,所有页面都包含[=36=]
<script type="module">
import Echo from 'laravel-echo'
window.io = require('socket.io-client');window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
window.Echo.channel('test-event')
.listen('ExampleEvent', (e) => {
console.log(e);
});
</script>
我创建了一个事件php artisan make:event ExampleEvent
如下
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class ExampleEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('test-event');
}
public function broadcastWith()
{
return [
'data' => 'Hi bro!'
];
}
}
和以下路线
Route::get('test-broadcast', function(){
broadcast(new \App\Events\ExampleEvent);
});
我还启动了一个队列监听器
php artisan queue:listen --tries=1
当我访问页面时 test-broadcast
我在终端中看到了这个
但是浏览器的控制台什么也没有显示,而 console.log(e);
必须 return 一些东西。我也是这样做的
window.Echo.channel('test-event')
.listen('ExampleEvent', (e) => {
alert('hi')
console.log(e);
});
但没有任何警报。听着好像有点问题
提前致谢。
更新
我在访问 login
或任何包含 app.blade.php
更新
我更新脚本代码如下
<script src="http://{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>
<script src="{{ asset('/js/app.js') }}"></script>
<script type="module">
import Echo from 'laravel-echo'
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
window.Echo.channel('test-event')
.listen('.ExampleEvent', (e) => {
console.log(e);
});
</script>
控制台仍然报错
TypeError: Error resolving module specifier: laravel-echo
更新
我运行
npm run development -- --watch
这是结果
cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch"
'cross-env' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/
setup/webpack.config.js "--watch"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Mamad\AppData\Roaming\npm-cache\_logs20-03-05T14_59_30_604Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ watch: `npm run development -- --watch`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ watch script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Mamad\AppData\Roaming\npm-cache\_logs20-03-05T14_59_30_697Z-debug.log
总的来说需要的是:
- 默认Laravel安装
- 作曲家要求predis/predis
- 安装 NPM 模块(laravel-echo-server,socket.io & laravel-echo)
通过控制台设置Laravel Echo Server(大部分为默认设置,域名除外):
{ "authHost": "http://echo", "authEndpoint": "/broadcasting/auth", "clients": [ { "appId": "fc3de97a1787ea04", "key": "ecf31edced85073f7dd77de1588db13b" } ], "database": "sqlite", "databaseConfig": { "redis": {}, "sqlite": { "databasePath": "/database/laravel-echo-server.sqlite" } }, "devMode": true, "host": null, "port": "6001", "protocol": "http", "socketio": {}, "secureOptions": 67108864, "sslCertPath": "", "sslKeyPath": "", "sslCertChainPath": "", "sslPassphrase": "", "subscribers": { "http": true, "redis": true }, "apiOriginAllow": { "allowCors": true, "allowOrigin": "http://echo:80", "allowMethods": "GET, POST", "allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id" } }
设置 Redis 服务器并使用 Laravel broadcasting.php 文件连接到它
'default' => env('BROADCAST_DRIVER', 'redis')
或BROADCAST_DRIVER=.env文件中的redis
- 在web.php 中添加路由
Route::get('/test-broadcast', function(){
broadcast(new \App\Events\ExampleEvent);
return response('OK');
});
- 在bootstrap.js中添加代码:
import Echo from 'laravel-echo'
window.io = require('socket.io-client');
window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001' });
已添加
window.Echo.channel('MyChannel') .listen('.ExampleEvent', (e) => { console.log(e); });
- 运行
npm run dev
编译所有 Javascript 模块 - 运行
laravel-echo-server start
启动 Laravel Echo Server - 运行
php artisan queue:listen --tries=1
启动监听队列 - 正在访问 http://echo/test-broadcast
已更新
11.1 将 ExampleEvent 的方法调整为:
public function broadcastOn() { return new Channel('MyChannel'); }
public function broadcastAs() { return 'ExampleEvent'; }
11.2 在welcome.blade.php中,在BODY标签前添加
<script type="text/javascript" src="/js/app.js"></script>
11.3 in database.php,设置redix前缀为空字符串值
'prefix' => env('REDIS_PREFIX', '')
不要忘记重新 运行 npm run dev
并清除浏览器缓存
结果
从你的错误来看,我认为你的包没有安装或导入不正确。您可以尝试安装包
npm install --save socket.io-client laravel-echo
将这些代码添加到 fileresources/js/bootstrap.js
的末尾import Echo from "laravel-echo"
window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
和运行npm run watch
参考:https://laravel.com/docs/master/broadcasting#driver-prerequisites部分socket.io