Laravel+Angular集成Pusher聊天时broadcasting/auth接口CORS报错
Laravel + Angular + Pusher 聊天功能CORS问题排查
问题背景
我基于Laravel+Angular+Pusher实现WebSocket聊天功能,Laravel端已完成配置:
- Postman调用
http://127.0.0.1/chatestb/public/broadcasting/auth接口,传入socket_id和频道名可正常返回认证信息:
{ "auth": "9d80a4aa39484cd65055:dbf25cefb383d8ec42c95e25d22d2dec3686a5de7fce4fc126a6c185c122ea10" }
- 消息发送功能正常
但Angular端通过Echo监听时触发CORS错误:
Access to XMLHttpRequest at 'http://localhost/chatestb/public/broadcasting/auth' from origin 'http://localhost:4200' 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. src\assets\js\pusher.min.js:8 POST http://localhost/chatestb/public/broadcasting/auth net::ERR_FAILED
已配置过CORS且其他接口正常,Angular端chat.component.ts相关代码如下:
echo!: Echo; inputMessage!: string; username = 'Najib'; allMessages: Messages[] = []; constructor(private chatService:ChatService,private tokenService:TokenService) { this.websocket(); } ngOnInit(): void { this.getGroupChat(); } websocket() { const token = this.tokenService.getToken(); this.echo = new Echo({ authEndpoint: `http://localhost/chatestb/public/broadcasting/auth`, auth: { headers: { Authorization: `Bearer ${token}` } }, broadcaster: 'pusher', key: '9d80a4aa39484cd65055', cluster: 'eu', wsHost: 'localhost', wsPort: 6001, forceTLS: false, disableStats: true, }); } getGroupChat() { this.echo.private('chat') .listen('ChatEvent', (res:any) => { const message: Messages = { message: res.message, me: false, from: res.from }; this.allMessages.push(message); }); }
解决方案
1. 确保CORS配置覆盖broadcasting/auth路由
Laravel默认CORS配置可能未包含/broadcasting/auth,修改config/cors.php:
// 新增broadcasting/auth到允许路径 'paths' => ['api/*', 'broadcasting/auth'], // 允许Angular的源地址 'allowed_origins' => ['http://localhost:4200'], // 开发环境可临时允许所有源:'allowed_origins' => ['*'], // 允许预检请求的方法 'allowed_methods' => ['*'], // 允许包含Authorization的请求头 'allowed_headers' => ['*'],
2. 统一域名避免CORS匹配问题
Postman使用127.0.0.1,Angular配置用localhost,CORS对域名严格匹配,修改Angular的Echo配置:
authEndpoint: `http://127.0.0.1/chatestb/public/broadcasting/auth`,
3. 确认CORS中间件生效
检查app/Http/Kernel.php的api中间件组是否包含HandleCors:
protected $middlewareGroups = [ 'api' => [ \Illuminate\Http\Middleware\HandleCors::class, // 其他中间件... ], ];
如果broadcasting/auth不在api路由组下,需单独为该路由添加CORS中间件(以routes/web.php为例):
Route::post('/broadcasting/auth', function () { return response()->json(request()->all()); })->middleware('cors');
4. 清除Laravel配置缓存
修改配置后执行命令刷新缓存:
php artisan config:clear php artisan cache:clear
内容的提问来源于stack exchange,提问作者marzouk najib
相关产品推荐
相关产品推荐

