GET and POST issue in laravel chat using Pusher and Vue.js - php

I have a problem following this tutorial to implement a simple chat in Laravel using Pusher and Vue.js: link tutorial.
First of all my route in the navbar is this one:
http://localhost/youChat/public/
My web.php file contents the following routes:
Auth::routes();
Route::get('/', 'TweetController#index');
Route::get('tweets', 'TweetController#showTweets')->middleware('auth');
Route::post('tweets', 'TweetController#sentTweet')->middleware('auth');
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', qs.stringify(tweet)).then(response => {
console.log(response.data);
});
}
}
});
As you can see I send the request with Axios.
Everything seems looks fine but the GET and POST request are not working. The error in the console inspector shows this:
GET http://localhost/tweets 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (app.js:13931)
at settle (app.js:35401)
at XMLHttpRequest.handleLoad (app.js:13805)
GET https://stats.pusher.com/timeline/v2/jsonp/1session=Njg3NjQyNDY5NT....MjY1fV0%3D 0 ()
POST http://localhost/broadcasting/auth 404 (Not Found)
And when I try to make a POST:
POST http://localhost/tweets 404 (Not Found)
The get/post should go to this direction:
http://localhost/youChat/public/tweets
but I don't know what's happening. Any suggestion? I'm desperated :D.
Thanks in advance!

You are getting this error because you are using an absolute path.
So either you can store the Base url in a variable or you can use relative path
here is an example.
methods: {
showTweets() {
axios.get('tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post('tweets', qs.stringify(tweet)).then(response => {
console.log(response.data);
});
}
}
Remove the / before the URL or
save a
const URL = '{{url('/')}}'
methods: {
showTweets() {
axios.get(URL + '/tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post(URL + '/tweets', qs.stringify(tweet)).then(response => {
console.log(response.data);
});
}
}
Hope this helps

Related

Vue axios 404 err

I have a problem when making an axios request, it returns a 404 error, the file path is fine since it is in the same directory and I do not understand why it returns that error,
I am using vue-cli, and I run the server with npm run serve instead of express.
Register.vue
var formData = new FormData();
formData.append("nombre", nombre);
formData.append("mail", mail);
formData.append("pass", pass);
axios
.post("./auth_register.php", formData)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
auth_register.php
<?php
if (isset($_POST['nombre']) && $_POST['mail'] && $_POST['pass']) {
return json_encode("received");
} else {
return null;
}
I don't know why this happens
I am new to vue do not be angry
Try using the full path; Worked for me! after long searching
example -> http://localhost:8080/api/authentication/login.php

Vue data does not display value on console but does display on component

I'm trying to retrieve a global session value and set it to the vue variable. The problem is, the id variable is not displaying any value on the console but does display the value on the vue component. I've checked with the vue devtools and the id does contain the correct value.
Vue Component
<template>
<div class="container">
<h1>{{id}}</h1> // the id does displays the value
</div>
</template>
<script>
export default {
data () {
return {
id:'',
}
},
created(){
axios.get('api/studentlecture').then(response => this.id = response.data).catch(function(error){console.log(error)
});
console.log(this.id)
},
methods:{
},
mounted() {
console.log('Component mounted.')
}
}
Controller
public function index()
{
$id= session('userID');
return json_encode($id);
}
Because the axios call is asynchronous. The JavaScript engine will execute the axios request, and while it is waiting it will continue executing the code.
You are trying to log this.id while it has not yet been assigned. If you want to log the value, you have to put it in the callback of your axios function.
axios.get('api/studentlecture')
.then(response => {
this.id = response.data;
console.log(this.id); // <== Here
})
.catch(function(error){console.log(error)});
This happens because console.log(this.id) is executed before axios.get() could resolve it's promise.
There are a few solution for this.
First one is to move console.log() inside then().
created() {
axios.get('api/studentlecture').then(response => {
this.id = response.data;
console.log(this.id);
}).catch(error => {
console.log(error)
});
}
Or you can make use of async/await to wait the promise to resolve
async created() {
try {
// This will wait until promise resolve
const response = await axios.get('api/studentlecture');
this.id = response.data;
console.log(this.id);
} catch(error) {
console.log(error)
}
}
You can learn more about promise here
And more about async/await difference with promise here
You can try using the following code below:
/*FRONT-END VUE*/
this.axios.get("https://localhost:8000/api/v1/data").then((response)=>{
this.data=response.data;
console.log(this.data);
if(this.data.success){
}
});
/*BACK-END LARAVEL*/
function getData(){
$result = array('success'=>true,'data'=>$data);
return Response()->json($result);
}

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!!

dropzone not uploading, 400 bad request, token_not_provided

okay i've been trying this for like 2 hrs now and cant to make this work. dropzone cant upload any file. the server says "token not provided". im using laravel as backend and it uses jwt tokens for authentication and angular as front end. here's my dropzone config.
$scope.dropzoneConfig = {
options: { // passed into the Dropzone constructor
url: 'http://localhost:8000/api/attachments'
paramName: 'file'
},
eventHandlers: {
sending: function (file, xhr, formData) {
formData.append('token', TokenHandler.getToken());
console.log('sending');
},
success: function (file, response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
}
};
and the route definition
Route::group(array('prefix' => 'api', 'middleware' => 'jwt.auth'), function() {
Route::resource('attachments', 'AttachmentController', ['only' => 'store']);
}));
and the controller method
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$file = Input::file('file');
return 'okay'; // just until it works
}
the token is correct and is actually getting to the server (because i tried returning the token using Input::get('token') in another controller function and it works). can someone tell me what im doing wrong? im getting "400 Bad Request" with "token_not_provided" message...
thanks for any help. and i apologize for my bad english..
I'm not sure why appending the token to the form isn't working, but you could try sending it in the authorization header instead.
Replace
formData.append('token', TokenHandler.getToken());
With
xhr.setRequestHeader('Authorization', 'Bearer: ' + TokenHandler.getToken());
make sure you add the token to your call: Example you can add the toke as a parameter in your dropzone url parameter.
//If you are using satellizer you can you this
var token = $auth.getToken();// remember to inject $auth
$scope.dropzoneConfig = {
options: { // passed into the Dropzone constructor
url: 'http://localhost:8000/api/attachments?token=token'
paramName: 'file'
},
eventHandlers: {
sending: function (file, xhr, formData) {
formData.append('token', TokenHandler.getToken());
console.log('sending');
},
success: function (file, response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
}
};

Defined route throwing controller method not found laravel 4

I have a route defined in routes.php file but when i make an ajax request from my angular app, i get this error
{"error":{"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException","message":"Controller method not found.","file":"C:\\xampp\\htdocs\\tedxph\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Controllers\\Controller.php","line":290}}
this is my routes file
/*
|--------------------------------------------------------------------------
| Api Routes
|--------------------------------------------------------------------------
*/
Route::group(array('prefix' => 'api'), function() {
//Auth Routes
Route::post('auth/login', 'ApiUserController#authUser');
Route::post('auth/signup', 'ApiUserController#registerUser');
/* Persons */
Route::group(array('prefix' => 'people'), function() {
Route::get('{id}', 'ApiPeopleController#read');
Route::get('/', 'ApiPeopleController#read');
});
/* Events */
Route::group(array('prefix' => 'events'), function() {
Route::get('{id}', 'ApiEventsController#read');
Route::get('/','ApiEventsController#read');
});
});
Accessing the same url (http://localhost/site/public/api/auth/signup) from a rest client app on chrome does not give any errors, what could be wrong?
this is the angular code from my controller
$rootScope.show('Please wait..registering');
API.register({email: email, password: password})
.success(function (data) {
if(data.status == "success") {
console.log(data);
$rootScope.hide();
}
})
.error(function (error) {
console.log(error)
$rootScope.hide();
})
more angular code
angular.module('tedxph.API', [])
.factory('API', function ($rootScope, $http, $ionicLoading, $window) {
//base url
var base = "http://localhost/tedxph/public/api";
return {
auth: function (form) {
return $http.post(base+"/auth/login", form);
},
register: function (form) {
return $http.post(base+"/auth/signup", form);
},
fetchPeople: function () {
return $http.get(base+"/people");
},
fetchEvents: function() {
return $http.get(base+"/events");
},
}
});
It'd help to see the code you're using to make the angular request, as well as the header information from Chrome's Network -> XHR logger, but my first guess would be Angular is sending the AJAX request with the GET method instead of the POST method. Try changing Angular to send an explicit POST or change routes.php so auth/signup responds to both GET and POST requests.
Update looking at your screen shots, the AJAX request is returning an error 500. There should be information logged to either your laravel.log file or your PHP/webserver error log as to why the error is happening. My guess if your Angular request sends different information that your Chrome/REST-app does, and that triggers a code path where there's an error.
Fixed the problem, turns my controller was calling an undefined method in the controller class.
Renamed the method correctly and the request now works, thanks guys for the input.

Categories