我正在使用Laravel作为后端API,这对Laravel广播是陌生的。
我正在创建一个广播频道,通过该频道,当创建新订单时,创建该订单的用户,相关商家和送货人员将收听此频道事件。
在OrderController.php中,
broadcast(new Ordered(Order::find($order->id)));
在BroadcastServiceProvider.php中,
public function boot()
{
Broadcast::routes(["prefix" => "api", "middleware" => "auth:api"]);
require base_path('routes/channels.php');
}
在laravel-echo-server.json中,
{
"authHost": "http://localhost/borneoshop/public",
"authEndpoint": "/api/broadcasting/auth",
"clients": [],
"database": "redis",
"databaseConfig": {
"redis": {
"port": "6379",
"host": "127.0.0.1"
},
"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": ""
}
}
在channels.php中,
Broadcast::channel('order.{id}', function (User $user, int $id) {
// this is for testing purpose as everyone is authenticated to listen to this channel
return true;
});
在laravel-echo-server控制台中,出现以下错误消息,出现500错误。
⚠ Starting server in DEV mode...
✔ Running at localhost on port 6001
✔ Channels are ready.
✔ Listening for http events...
✔ Listening for redis events...
Server ready!
[12:49:35 PM] - Preparing authentication request to: http://localhost/borneoshop/public
[12:49:35 PM] - Sending auth request to: http://localhost/borneoshop/public/api/broadcasting/auth
⚠ [12:49:35 PM] - dmkSogBCuO0vabInAAAA could not be authenticated to private-order.36
{
"message": "Argument 1 passed to App\\Providers\\BroadcastServiceProvider::{closure}() must be an instance of User, instance of App\\Models\\Auth\\User\\User given, called in C:\\xampp\\htdocs\\borneoshop\\vendor\\laravel\\framework\\src\\Illuminate\\Broadcasting\\Broadcasters\\Broadcaster.php on line 77",
"exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
"file": "C:\\xampp\\htdocs\\borneoshop\\routes\\channels.php",
"line": 34,
在index.js中,我已经创建了它以测试广播API,稍后将在Flutter项目中将其实现
const express = require('express');
const Echo = require('laravel-echo');
const io = require('socket.io-client');
const echo = new Echo({
broadcaster: 'socket.io',
host: 'http://192.168.1.14:6001',
client: io,
auth : {
headers : {
// the current logged-in user token
Authorization : "Bearer ******"
}
}
});
// I set the order value here as for testing of the newly created order
const id = 36;
echo.private(`order.${id}`)
.listen('.OrderedEvent', (e) => {
console.log(e);
});
由于不需要身份验证和授权,因此它在公共频道上可以很好地工作,但是当我切换到私有频道时,HTTP 500响应代码会出错。