"laravel-echo": "^1.6.0",
"pusher-js": "^5.0.2",
I am using Laravel WebSockets to send events to my Vue.js app using Laravel Echo as:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
First of all when I connect my app, I see this message:
Connection id 473581849.201555836 sending message {"event":"pusher:connection_established","data":"{\"socket_id\":\"473581849.201555836\",\"activity_timeout\":30}"}
When I disconnect, I see this one:
Connection id 603442282.571320345 closed.
So the app is well communicating with the Laravel WebSocket, no problem with that as it received the connection and connection packets from my app.
My problem comes when I try to read in my front end a packet from the server, I just cannot get it.
const echo = new Echo({
broadcaster: 'pusher',
cluster: process.env.WEBSOCKET_CLUSTER,
key: process.env.WEBSOCKET_KEY,
wsHost: process.env.WEBSOCKET_URL,
wssHost: process.env.WEBSOCKET_URL,
wsPort: process.env.WEBSOCKET_PORT,
wssPort: process.env.WEBSOCKET_PORT,
encrypted: process.env.WEBSOCKET_ENCRYPTED,
disableStats: process.env.WEBSOCKET_DISABLE_STATS,
enabledTransports: ['ws', 'wss']
// auth: {
// headers: {
// 'Accept': 'application/json',
// 'Authorization': 'Bearer ' + window.localStorage.getItem('accessToken')
// }
// }
});
export default ({ Vue }) => {
Vue.prototype.$echo = echo;
};
Here is for example an event received(this is what I get from the ssh console):
Connection id 545411452.62710705 sending message {"event":"log-message","channel":"private-websockets-dashboard-api-message","data":{"type":"api-message","time":"20:06:24","details":"Channel: androidMobile, Event: App\\Events\\UpdateAndroidNavBarCounts","data":"{\"message\":{\"countincompletereports\":0,\"countviewmyreports\":1002,\"countpoints\":300,\"user_id\":63}}"}}
This event here: App\Events\UpdateAndroidNavBarCounts
I cannot get it in my front end, I tried this:
this.$echo.channel('androidMobile')
.listen('.App.Events.UpdateAndroidNavBarCounts', function (data) {<------------
console.log('This is a test 2');
this.$store.dispatch('common/UpdateAndroidNavBarCounts', data, { root: true });
})
this
this.$echo.channel('androidMobile')
.listen('App.Events.UpdateAndroidNavBarCounts', function (data) {<------------
console.log('This is a test 2');
this.$store.dispatch('common/UpdateAndroidNavBarCounts', data, { root: true });
})
this:
this.$echo.channel('androidMobile')
.listen('.UpdateAndroidNavBarCounts', function (data) {<------------
console.log('This is a test 2');
this.$store.dispatch('common/UpdateAndroidNavBarCounts', data, { root: true });
})
and even this:
this.$echo.channel('androidMobile')
.listen('UpdateAndroidNavBarCounts', function (data) { <------------
console.log('This is a test 2');
this.$store.dispatch('common/UpdateAndroidNavBarCounts', data, { root: true });
})
I never managed to see the console.log('This is a test 2'); message.
Any help would be appreciated please as I have been struggling on this for days and days and I am starting to believe that it is a bug.
Thank you.
oK, with time I worked it out ...
I was using the Quasar framework and this was the top of my boot file:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Pusher.logToConsole = true;
When I added this logToConsole = true; parameter, I could start seeing the communication from the Android mobile to the API.
My problem was this:
authEndpoint: process.env.WEBSOCKET_AUTH_URL
let's say WEBSOCKET_AUTH_URL = https://mywebsite.com
No idea why but if I add this:
authEndPoint: process.env.WEBSOCKET_AUTH_URL + '/broadcasting/auth'
It does not work, the url is broken into 2 strings.
I also tried this:
authEndPoint: JSON.stringify(process.env.WEBSOCKET_AUTH_URL) + '/broadcasting/auth'
No luck either, so instead I added the whole url in the .env file as:
WEBSOCKET_AUTH_URL = https://mywebsite.com/broadcasting/auth
Now it works.
Related
Hi developers I have currently problem this project is an old project where the developer created. right now, we need to adjust some of there functionality. Right now I already extract the files to my localhost folder and now work without error on run watch and artisan serve. So the problem here is on login on the console it shows that http://localhost:8000/project/oauth/token 405 (Method Not Allowed), I really don't understand why this shows on the localhost however on the live server it works.
This project created using Vue Js and Laravel for the backend.
I will show you guys the authentication function.
Login Function:
authenticate(){
this.login_alert = false
this.$validator.validateAll().then((result)=>{
if(result){
const self = this;
const authUser = {}
try{
const data = {
username: this.email,
password: this.password,
remember: this.remember_me,
client_id: '2',
client_secret: 'secret',
grant_type : 'password',
scope : ''
}
this.$store.dispatch('AUTH_REQUEST',data)
.then(response=>{
console.log(data);
authUser.access_token = response.access_token
authUser.refresh_token = response.refresh_token
authUser.expires_in = response.expires_in
window.localStorage.setItem('project_token',JSON.stringify(authUser))
/*LOGIN*/
this.login_alert = false
this.loading = false
window.location.reload()
})
.catch(error=>{
this.login_alert = true
window.localStorage.removeItem('project_token')
this.loading = false
})
}catch(err){
console.log(err);
}
}
})
}
For the AUTH REQUEST:
AUTH_REQUEST:({commit,dispatch},obj)=>{
return new Promise((resolve,reject) => {
axios({
url: '/project/oauth/token',
data: obj,
method:'post',
config:'JSON'
})
.then(response=>{
if(response.status == 200){
resolve(response.data);
}
})
.catch(error=>{
reject(error);
localStorage.removeItem('project_token');
commit('AUTH_ERROR',error);
})
})
},
Hope some one experience this. thanks.
In my case, the compilation of the route should be specified properly, for example
async purchaseDelete(purchase) {
Csrf.getCookie();
return Api.delete('/api/purchase_settings/${purchase.id}');
},
the single tick on the axios delete method didnt represent correctly
async purchaseDelete(purchase) {
Csrf.getCookie();
return Api.delete(`/api/purchase_settings/${purchase.id}`);
}
When changed to back ticks, it responded with the correct result
I recently worked on a notification system using Pusher and Laravel. unfortunately can't make it work this way:
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
Pusher.logToConsole = true;
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'WORKING KEY ..',
cluster : "mt1",
encrypted: true
});
and
window.Echo.channel('post')
.listen('ArticleEvent', function (e) {
console.log(e);
});
While messages was sent to client console, but Listen didn't worked at all... and nothing logged.
anyway I used this way and it worked:
window.Pusher = require('pusher-js');
var pusher = new Pusher('WORKING KEY ..', {
encrypted: true,
cluster: 'mt1',
});
var channel = pusher.subscribe('post');
channel.bind('ArticleEvent', function(e) {
alert(JSON.stringify(e['message']));
});
What is deference between 2 ways and which must be preferred?
You need to include namespace information in the Listen method.
Please try using (note the . character):
window.Echo.channel('post')
.listen('.ArticleEvent', function (e) {
console.log(e);
});
So, I'm learning how to create Single Page Applications using Laravel & Vue.js, and I found this tutorial. I followed everything, I didn't change anything but I keep getting this undefined whenever I will login/register
I've double-triple checked everything.
Image showing the http://127.0.0.1:8080/undefined/api/auth/login -
https://imgur.com/LfpiMvS
Here's the code:
Auth.js
import bearer from '#websanova/vue-auth/drivers/auth/bearer'
import axios from '#websanova/vue-auth/drivers/http/axios.1.x'
import router from '#websanova/vue-auth/drivers/router/vue-router.2.x'
// Auth base configuration some of this options
// can be override in method calls
const config = {
auth: bearer,
http: axios,
router: router,
tokenDefaultName: 'recipe-lists',
tokenStore: ['localStorage'],
rolesVar: 'role',
registerData: {url: "auth/register", method: 'POST', redirect: '/login'},
loginData: {url: "auth/login", method: 'POST', redirect: '/', fetchUser: true},
logoutData: {url: "auth/logout", method: 'POST', redirect: '/', makeRequest: true},
fetchData: {url: "auth/user", method: 'GET', enabled: true},
refreshData: {url: "auth/refresh", method: 'GET', enabled: true, interval: 30}
}
export default config
api.php
Route::prefix('auth')->group(function () {
Route::post('register', 'Auth\AuthController#register');
Route::post('login', 'Auth\AuthController#login');
Route::get('refresh', 'Auth\AuthController#refresh');
Route::group(['middleware' => 'auth:api'], function(){
Route::get('user', 'Auth\AuthController#user');
Route::post('logout', 'Auth\AuthController#logout');
});
});
login.vue
<script>
export default {
data() {
return {
email: null,
password: null,
has_error: false,
isProcessing: false,
}
},
methods: {
login() {
// Get the redirect object
this.isProcessing = true
var redirect = this.$auth.redirect()
this.$auth.login({
body: {
email: this.email,
password: this.password
},
success: function() {
// Handle Redirection
const redirectTo = redirect ? redirect.from.name : this.$auth.user().role === 2 ? 'admin.dashboard' : 'dashboard'
this.$router.push('/')
},
error: function() {
this.has_error = true
},
rememberMe: true,
fetchUser: true
})
}
}
}
</script>
Can someone explain to me what's happening pretty noob here.
Thank you!
I expected the url to be http://127.0.0.1:8080/api/auth/login
I've faced a similar problem with the undefined part in URL.
The reason was that I did not have the MIX_APP_URL variable set up in my .env Laravel configuration file.
The way ${process.env.MIX_APP_URL} works is that an environment variable can be injected by Node at runtime, in this case the application url.
One reason we want the MIX_APP_URL in .env is that any developer using your application can easily set it up and only modify the MIX_APP_URL variable.
The other, very important reason is that the URL will differ for a local server and for production - in this case the solution to change it to a static URL would not work and would be prone to an error in a production environment.
One thing to notice though, when running the NPM watch task, the change of an .env variable does not apply immediately, the watch task has to be restarted.
It turns out my error was from my app.js, the code is:
axios.defaults.baseURL = `${process.env.MIX_APP_URL}/api`
After I changed it to:
axios.defaults.baseURL = `http://127.0.0.1:8000/api`
It worked, the undefined thingy is now gone. I didn't know why the first one didn't work but meh.
Reddit user /u/mrcat323 helped me get an answer in /r/vuejs.
I am using nuxt/laravel api with laravel-echo-server and socket.io-client.
When I use it this way:
import Echo from 'laravel-echo'
if (process.client) {
window.io = require('socket.io-client')
window.Echo = new Echo({
broadcaster: 'socket.io',
host: 'http://seekers-backend.com:6001',
auth: { headers: { Authorization: 'Bearer-token' } }
})
}
And then use window.Echo.private().listen().... it works perfectly..
But when I try to declare it within data property I get error because that is rendered on server side... How can I use socket.io-client on server side rendering or how can I declare it on client side since I need access to getters for Bearer token.
I guess I found the way that works for unknown reason :D
import Echo from 'laravel-echo'
if (process.client) {
window.io = require('socket.io-client')
}
And then
mounted() {
let echo = new Echo({
broadcaster: 'socket.io',
host: 'http://seekers-backend.com:6001',
auth: { headers: { Authorization: this.token } }
})
echo.private('user.' + this.$auth.user.id)
.listen('MessageEvent', (e) => {
// Do stuff
})
}
i did implement a broadcast notification in my application with pusher. it is in live. it work good but the problem is when i logout from pusher or close the pusher window then the can't get the notification. if i again login into pusher then notification work.
in blade:
Echo.channel('NotificationChannel')
.listen('NotificationEvent', (e) => {
if( {{Auth::user()->id}} == e.to_doctor_notification.id){
toastr.success('You have a new patient request.', e.to_doctor_notification.name, {timeOut: 50000, progressBar: true, positionClass: 'toast-bottom-left', closeButton: true, newestOnTop: true, extendedTimeOut: 100000})
};
});
In controller:
broadcast(new NotificationEvent($to_doctor_notification));
in NotificationEvent:
public function broadcastOn(){
return new Channel('NotificationChannel');
}
In bootstrap.js:
import Echo from "laravel-echo"
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'app-key',
cluster: 'ap2',
encrypted: true
});
I solve this problem. I have too many javascript file included. that why it doesn't work.
i include the pusher link
this is pusher link
Those are Notification received code in which page want to see the notificetion.
<script>
var pusher = new Pusher('app-key', {
cluster: 'ap2',
forceTLS: true
});
var channel = pusher.subscribe('NotificationChannel');
channel.bind('EchoEvent', function(e) {
if( {{Auth::user()->id}} == e.to_doctor_notification.id){
toastr.success('You have a new patient request.', e.to_doctor_notification.name, {timeOut: 50000, progressBar: true, positionClass: 'toast-bottom-left', closeButton: true, newestOnTop: true, extendedTimeOut: 100000})
};
});