- Pusher Tutorial

 

Build Online Presence Into Your Laravel App 
https://pusher.com/tutorials/online-presence-laravel


Realtime User Status Update using Laravel and Pusher
viraj-khatavkar/user-status-update-laravel-pusher
https://github.com/viraj-khatavkar/user-status-update-laravel-pusher


- 채널을 안 만들고 클라이언트들 끼리 통신

api_token 사용법 유용



//=============
.env , /resources/assets/js/bootstrap.js 파일 에 pusher 정보 수정

test DB 수정
- users : api_tocken : not null -> false

//=============
composer
composer.json 수정
composer update


//=============
npm
package.json 수정
npm update


//===================================
//===================================
< 동작 흐름 >

- 채널로 들어감
- Example.vue 파일

mounted() {
            this.listen(); //

        },
        methods: {
            listen() {
                Echo.join('chat') // 프레젠스 채널로 들어감
                    .joining((user) => { // 채널에 사용자가 들어왔을때 이벤트
                        console.log('joining', user);
// api 호출
                        axios.put('/api/user/'+ user.id +'/online?api_token=' + user.api_token, {});
                    })
    .leaving((user) => { // 사용자 나감
                        console.log('leaving', user);
                        axios.put('/api/user/'+ user.id +'/offline?api_token=' + user.api_token, {});
                    })
                    .listen('UserOnline', (e) => { //'UserOnline' 이벤트, 라라벨에서 지정
                        console.log('listen - UserOnline', e);
                        this.friend = e.user;
                    })
                    .listen('UserOffline', (e) => {
                        console.log('listen - UserOffline', e);
                        this.friend = e.user;
                    });

            },


//========
- 채널 인증
//==============
- 서버측 인증 , 라라벨

- 라라벨 사용시
BroadcastServiceProvider.php 파일에서 
인증경로가  '/broadcasting/auth' 자동 생성됨
인증을 시도하면 routes/channels.php 파일에서 처리

- routes/channels.php 파일
Broadcast::channel('chat', function ($user) {
    return $user;
});

//===========
* api 호출
- 클라이언트
axios.put('/api/user/'+ user.id +'/online?api_token=' + user.api_token, {});


- 서버
- UserOnlineController.php 파일

broadcast(new UserOnline($user)); // 메지지 보내기 (브로드캐스트 이벤트 발생)


- app/Events/UserOnline.php 파일

public function broadcastOn()
    {
        return new PresenceChannel('chat');//채널에 메시지 보내기
    }



//===================================
//===================
http://localhost/home 에러
[Vue warn]: failed to compile template:

laravel-mix

npm run dev 
- 에러
Error: Cannot find module \node_modules\cross-env\bin\cross-env.js

.env 파일 수정
node_modules\cross-env\bin\cross-env.js
-> node_modules\cross-env\dist\bin\cross-env.js


//==========================
- 에러 
app.js Pusher : Error : {"type":"WebSocketError","error":{"type":"PusherError","data":{"code":4001,"message":"App key  not in this cluster. Did you forget to specify the cluster?

- 해결 방법
/resources/assets/js/bootstrap.js 파일에 다음을 추가

window.Pusher = require('pusher-js');

- 다시 빌드
npm run dev

 


//=================
- 에러 
- console 메시지
Uncaught ReferenceError: Pusher is not defined


this.pusher = new Pusher(this.options.key, this.options);
            }


- 해결 : bootstrap.js 에 추가
import Pusher from 'pusher-js'



//================
- 에러
user2 에러
- 해결 : 사용자가 2명 이상 등록되면 된다.



//================
- 에러
api_token 에러

- 해결책
DB , users 테이블에 api_tocken 칼럼에 랜덤 값은 넣는다.
nIq42BjLvGqo6lJ42iny22PVcZwa0cqeZhlJiuu3neyh1JWZiMkevRTjVOPp


- 근본적인 해결책 : 
 app\Http\Controllers\Auth\RegisterController.php 파일 수정

protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'api_token' => Str::random(60),  // <====== 추가
        ]);
    }


//================
- 에러
- 에러 : npm run dev

internal/modules/cjs/loader.js:628
    throw err;
    ^

Error: Cannot find module node_modules\cross-env\dist\bin\cross-env.js

- 해결방법 :
- laravel-mix 버전을 4로 올린후 발생
npm install --save-dev cross-env


- 이상한 에러가 계속 생기면 packae.json 수정

"laravel-mix": "^0.8",
테스트 결과 에러 안나는 버전 : v1, v2, v3 까지 에러 안남

laravel-mix v4로 올리면 에러 발생




//=====================
- 에러

> node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

\node_modules\webpack-cli\bin\cli.js:93
                                throw err;

TypeError: Cannot read property 'js' of undefined
    at Object. ( \webpack.mix.js:14:5)


- 해결방법
- 원인 :  laravel-mix v4로 올리면 에러 발생

werppack.mix.js 파일 수정
//const { mix } = require('laravel-mix'); //v3 이하
const mix = require('laravel-mix'); //v4 이상




//================
- 에러
[Vue warn]: Error in mounted hook: "TypeError: this.listenForWhisper is not a function"

- 에러
Property or method "whisper" is not defined
 Error in v-on handler: "TypeError: _vm.whisper is not a function"


- Example.vue 파일 수정
Vue method 추가

,
        methods: {
            ...

            whisper() {
                Echo.private('chat')
                    .whisper('typing', {
                        name: this.user.name
                    }); 
            },
            listenForWhisper() {
                Echo.private('chat')
                    .listenForWhisper('typing', (e) => {
                        console.log(e.name);
                    });
            },


//==============================
- 에러
FatalThrowableError in HomeController.php line 41:
Class 'Pusher\Pusher' not found

- 증상
composer.json 파일에
"pusher/pusher-php-server": "^3.0", 가 있고
composer update 명령을 했는데도 안되면 pusher-php-server 패키지 재설치


- 재설치
composer remove pusher/pusher-php-server

composer.lock 파일 삭제
vendor/pusher 폴더 삭제

composer.json 파일에
"pusher/pusher-php-server": "^3.0", 추가
composer update



//==============================
- 에러

In BroadcastManager.php line 

  Broadcaster [] is not defined.


- 해결 방법
.env 파일 수정
BROADCAST_DRIVER=log



//==============================
- 에러

[Vue warn]: Failed to mount component: template or render function not defined. found in example


- 원인 : laravel-mix 4 부터 .default가 필요

- 해결 방법 : 
resources/assets/js/app.js 파일 수정

Vue.component('example', require('./components/Example.vue') );
-> Vue.component('example', require('./components/Example.vue').default ); // .default 추가


 

Posted by 코덴스

댓글을 달아 주세요