Laravel Echo 500 error (broadcasting/auth)? - php

have a nice day !
I have a problem:
I set up Laravel Echo & Pusher but got this error, have no idea to resolve :(
I checked my app-key, app-cluster but all are correct.
Can someone help me?
app.js
const app = new Vue({
el: '#app',
data: {
messages: []
},
methods:{
addMessage(message){
this.messages.push(message);
axios.post('/messages', message).then(response => {
console.log(response);
});
}
},
created(){
axios.get('/messages').then(response => {
this.messages = response.data;
});
Echo.channel('chatroom')
.listen('MessageEvent', (e) => {
console.log(e);
});
}
})
bootstrap.js
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: '************',
cluster: 'ap1',
encrypted: false
});
MessageEvent
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message, $user;
public function __construct(Message $message, User $user)
{
$this->message = $message;
//query
$this->user = $user;
}
public function broadcastOn()
{
return new PresenceChannel('chatroom');
}
channels.php
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Broadcast::channel('chatroom', function ($user, $id) {
return $user;
});

Error 403 or 500 /broadcasting/auth with Laravel version > 5.3 & Pusher, you need change your code in resources/assets/js/bootstrap.js with
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your key',
cluster: 'your cluster',
encrypted: true,
auth: {
headers: {
Authorization: 'Bearer ' + YourTokenLogin
},
},
});
And in app/Providers/BroadcastServiceProvider.php change by
Broadcast::routes()
with
Broadcast::routes(['middleware' => ['auth:api']]);
or
Broadcast::routes(['middleware' => ['jwt.auth']]); //if you use JWT
it worked for me, and hope it help you.

Remove the $id as you are not passing from the event
Broadcast::channel('chatroom', function ($user) {
return true;
});

I think you need to give an authentic point if u have used laravel echo just goto
Resources/assets/js/bootstrap.js
Just add the following line inside the window
Echo = new Echo({
authEndpoint : 'http://localhost/projectName/public/broadcasting/auth',
});

if you're working on localhost make sure that your .env file is set up properly
try setting
APP_URL=http://localhost
DB_HOST=localhost
and run
php artisan config:cache
hope this will help you.

Related

There is Error 500 when sending message with axios and pusher

I trying to create CHAT in fresh Laravel 6.0 framework.
I following this tutorial https://pusher.com/tutorials/chat-laravel
Routes file, web.php
Route::get('messages', 'ChatsController#fetchMessages');
Route::post('messages', 'ChatsController#sendMessage');
JavaScript files
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
import Pusher from 'pusher-js';
Echo.private('chat').listen('MessageSent', (e) => {
this.messages.push({
message: e.message.message,
user: e.user
});
});
import Echo from "laravel-echo"
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'xxxxxx',
cluster: 'eu',
encrypted: false,
useTLS: false
});
const app = new Vue({
el: '#app',
data: {
messages: []
},
created() {
this.fetchMessages();
},
methods: {
fetchMessages() {
axios.get('messages').then(response => {
this.messages = response.data;
});
},
addMessage(message) {
this.messages.push(message);
axios.post('messages', message).then(response => {
console.log(response.data);
});
}
}
});
BroadcastServiceProvider.php
class BroadcastServiceProvider extends ServiceProvider
{
public function boot()
{
Broadcast::routes();
Broadcast::channel('chat', function ($user) {
return Auth::check();
});
}
}
MessageSent.php Event
public function broadcastOn()
{
return new PrivateChannel('chat');
}
MySQL input works but fetch on another browser NO!
There is Error 500 in Console Log
POST http://localhost:8000/messages 500 (Internal Server Error)<br>
Uncaught (in promise) Error: Request failed with status code 500<br>
at createError (createError.js?2d83:16)<br>
at settle (settle.js?467f:17)<br>
at XMLHttpRequest.handleLoad (xhr.js?b50d:59)<br>
There is fresh laravel log file: https://pastebin.com/vnjNUd2n

Error 500 Axios POST Request in Laravel chat using Pusher and Vue.js

I have a problem following this tutorial to implement a simple chat in Laravel using Pusher and Vue.js: Link tutorial.
My app.js file in assets/js where I make the request is this one:
const app = new Vue({
el: '#app',
data: {
tweets: []
},
created() {
this.showTweets();
Echo.private('chat')
.listen('TweetSentEvent', (e) => {
this.tweets.push({
tweet: e.tweet.tweet,
user: e.user
});
});
},
methods: {
showTweets() {
axios.get('/tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post('tweets', tweet).then(response => {
console.log(response.data);
});
}
}
});
My web.php routes:
Auth::routes();
Route::get('/', 'TweetController#index');
Route::get('tweets', 'TweetController#showTweets')-
>middleware('auth');
Route::post('tweets', 'TweetController#sentTweet
My controller is this one:
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('chat');
}
public function showTweets(){
return Tweet::with('user')->get();
}
public function sendTweet(Request $request){
$user = Auth::user();
$tweet = $user->tweets()->create([
'tweet' => $request->input('tweet')
]);
broadcast(new TweetSentEvent($user, $tweet))->toOthers();
//return ['status' => 'Tweet Sent!'];
}
When I'm running the app and I try to send a tweet through a POST request clicking on my send button, this error apperas on the console:
POST http://localhost/youChat/public/tweets 500 (Internal Server Error)
Uncaught (in promise) Error: Request failed with status code 500
at createError (app.js:13931)
at settle (app.js:35401)
at XMLHttpRequest.handleLoad (app.js:13805)
Everything seems to be fine... Any help? Thanks in advance!!

Ionic 2 Login using Phone Number

I am doing ionic 2 login using phone number and password. I am using Laravel 5.3 passport as backend. As login is functioned using postman. but in ionic 2 it gives me error as -
Unexpected token < in JSON at position 0
at JSON.parse ()
at Response.Body.json (http.es5.js:800) at SafeSubscriber._next (register-api.ts:33)
my code is given below-
loginData = { contact:'', password:'' };
login.ts code
doLogin() {
this.showLoader();
this.registerApi.login(this.loginData).then((result) => {
this.loading.dismiss();
this.data = result;
this.viewCtrl.dismiss().then(
(result) => this.app.getRootNav().setRoot(MyApp)
)
window.location.reload();
}, (err) => {
this.loading.dismiss();
this.presentToast(err);
}); }
registerapi.ts code
login(credentials) {
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post(apiUrl+'login', JSON.stringify(credentials), {headers: headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
}); }
I am really stuck here.. Thank You.
MY php laravel code is as -
public function login(){
if(Auth::attempt(['contact' => request('contact'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['fname'] = $user->fname;
$success['lname'] = $user->lname;
$success['contact'] = $user->contact;
$success['id'] = $user->id;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
< in JSON at position 0 Means that most probably you are getting HTML body from the server, due to wrong link apiUrl (maybe instead of apiUrl +'login' should be apiUrl +'/login') or there is an php error, try following code to see the exact response in the console:
login(credentials) {
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post(apiUrl+'login', JSON.stringify(credentials), {headers: headers})
.subscribe(res => {
console.log(res.text());
}, (err) => {
reject(err);
});
}); }

How to bind "pusher:subscribe" event , using Laravel's Echo

In my laravel application i am using laravel ECHO. In this I'm trying to listen a event "pusher:subscribe" through on method. But I its not happening. I can able to subscribe, add_memeber, remove_memeber as per laravel echo documentation. But i cannot able to listen specifically "pusher:subscribe" event. Actually I am trying to get data from this event and i will manipulate further
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'myKeyHere',
authEndpoint: 'pusher/auth',
auth: {
headers: {
},
params: {
username: this.username
}
}
});
window.Echo.join('openChat').here((users) => {
console.log(users);
}).listen('MessagePublished', (e) => {
console.log('Message Received');
}).on('pusher:subscribe', (users) => {
console.log('NOT WORKING');
}).joining((user) => {
console.log('User Joined');
}).leaving((user) => {
console.log('User gone');
});
After a deep lookup in documents and forums i understood pusher:subscribe is a internal event , so it cannot be captured through Laravel ECHO. But I used pusher:subscription_succeeded to capture the member info ..
Modified Code:
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'myKeyHere',
authEndpoint: 'pusher/auth',
auth: {
headers: {
},
params: {
username: this.username
}
}
});
window.Echo.join('openChat').here((users) => {
console.log(users);
}).listen('MessagePublished', (e) => {
console.log('Message Received');
}).on('pusher:subscription_succeeded', (member) => {
console.log(member);
}).joining((user) => {
console.log('User Joined');
}).leaving((user) => {
console.log('User gone');
});

Laravel/angular - 400 bad request

I am making an app in ionic and the backend is made in Laravel. I am working on a password reset functionality, and I keep getting the above mentioned error, when I am testing endpoints in chrome. This is the code for the contact information function:
sendContactConfirmation: function(contact, reset) {
var defer = $q.defer();
if(reset == 'reset'){
var endpointUrl = $http.post(AppSettings.apiUrl + "/users/reset", { phone: contact });
}
else {
var endpointUrl = $http.post(AppSettings.apiUrl + "/users", { phone: contact });
}
endpointUrl.then(function(result) {
service.set(result.data.user);
defer.resolve(result);
}, function(error) {
defer.reject(error);
});
return defer.promise;
},
And these are the routes in my Laravel back-end:
Route::group(['jwt.auth', ['except' => ['authenticate']], 'prefix' => 'api', 'namespace' => 'Api'], function() {
Route::post('authenticate', 'AuthenticateController#authenticate');
Route::get('authenticate/user', 'AuthenticateController#getAuthenticatedUser');
Route::post('users', 'UsersController#register');
Route::post('users/reset', 'UsersController#resetContact');
Route::put('users/{user}/reset', 'UsersController#resetPassword');
Route::put('users/{user}', 'UsersController#update');
Route::put('users/{user}/activate', 'UsersController#activate');
Route::post('users/{user}/pic', 'UsersController#uploadPicture');
});
And this is the resetContact function:
public function resetContact(Request $request)
{
$this->validate(
$request,
['phone' => 'required|regex:/^[0-9]{8}$/']
);
$user = User::where('phone', $request->get('phone'))->firstOrFail();
if ($user) {
try {
$this->sendValidationCode($user, 'reset');
}
catch (\Exception $e) {
throw new ApiException($e->getMessage(), 500);
}
}
return response()->json([
'user' => $user,
]);
}
Not sure why do I get this 400 Bad request error for this.
When using Laravel JWT make sure you always send the token for all routes under jwt.auth otherwise you will get the error 400 = Token not provided. In ionic make sure your toke is provided on each call to your laravel endpoint to avoid this error.

Categories