我知道我不是第一个为此苦苦挣扎的人。但是经过几天并解决了很多相关问题后,我不知何故觉得我的案子值得提出自己的问题:)。
我有一个使用 Laravel Websockets ( https://beyondco.de/docs/laravel-websockets/getting-started/introduction ) 和 Laravel Echo 的公共频道的工作 websocket 解决方案。我的客户端应用程序是一个 vue-cli 应用程序,它连接到服务器 + 公共频道上的广播消息效果很好。授权由 Laravel Passport 处理。因此,通过在 Authorization 标头中发送 Bearer 令牌,后端应用程序知道用户是否已通过身份验证。
但是,我正在努力让私人频道正常工作。尝试进行身份验证总是给我这个错误:
Access to XMLHttpRequest at 'https://my-app.test/broadcasting/auth' from origin 'https://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我知道当我遇到服务器问题时会出现这个 CORS 错误,所以我尝试在 Insomnia 中调试请求。但是,当模仿 Insomnia 中的请求时,它会给出响应 200 以及预期的结果:
我一直在阅读一些指南和 stackoverflow 问题,但找不到类似的东西。回到它可能是一个 CORS 问题,但我认为情况并非如此。我的 OPTIONS 请求返回就好了。
为了完整起见,我还添加了一些可能有助于调试的代码。
我的广播服务提供者
public function boot()
{
Broadcast::routes(['middleware' => ['auth:api']]);
require base_path('routes/channels.php');
}
我的频道.php
use Illuminate\Support\Facades\Broadcast;
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
客户端
this.echoClient = new Echo({
broadcaster: 'pusher',
key: process.env.VUE_APP_WEBSOCKETS_APP_ID,
wsHost: process.env.VUE_APP_WEBSOCKETS_URL,
wssPort: 6001,
// forceTLS: true,
disableStats: true,
authEndpoint: process.env.VUE_APP_SERVER_URL + '/broadcasting/auth',
auth: {
headers: {
Authorization: "Bearer " + this.$store.state.auth.auth_token
}
}
})
// this one works!!
this.echoClient.channel('App.User')
.listen('UpdatePosts', (e) => {
console.log('event received')
console.log(e)
})
// private channels don't work ... :'(
this.echoClient.private('App.User.' + this.user.id)
.listen('UpdatePosts', function(e) {
console.log(e)
})