this.$http vueJs not set - ajax

I'm playing with vueJS and trying to grab some data from an ajax request.
Heres my code:
new Vue({
el: '#recipeList',
ready: function () {
this.fetchRecipes();
},
methods: {
fetchRecipes: function () {
this.$http.get('/recipes/ajax', function (recipes) {
this.$set('recipes') = recipes;
});
}
}})
The html code is fine, I doubt you need to see that.
The documentation says that this is how you do a ajax request, however the $http object does not appear to be set.
Here is the console error I am receiving:
TypeError: undefined is not an object (evaluating 'this.$http.get')
fetchRecipesapp.js:10
(anonymous function)vue.js:307
readyapp.js:5
_callHookvue.js:8197
readyvue.js:10169
$mountvue.js:10155
_initvue.js:8054
Vuevue.js:80
global codeapp.js:1
app.js:10

$http.get is for Vue Resource. Make sure you are pulling that in properly. i.e., add vue-resource to your package.json, then npm install, then...
var Vue = require('vue');
Vue.use(require('vue-resource'));
Also, make sure your root path is set up properly.
Vue.http.options.root = '/your-root-path';
Hope it helps! :-)

Related

Vue error for pagination: response is not defined

I keep getting this Vue error: "ReferenceError: response is not defined" but when I check in the console, the data is all there.
I intend to use the data from the response to make pagination. Thanks in advance.
Methods
getAllUserData(){
let $this=this;
axios.get('api/members/getAllMembersData').then(response=>this.members=response.data.data);
$this.makePagination(response.meta,response.links);
},
makePagination(meta,links){
let pagination={
current_page:meta.current_page,
last_page:meta.last_page,
next_page_url:links.next,
prev_page_url:links.prev
}
this.pagination = pagination;
}
axios.get() is an async function. The code that follows this function will not be executed after the ajax request completes, but long before that. Because of this, the variable response does not exist yet.
All code that has to be executed when the ajax call completes has to be put in the .then() function of the call.
getAllUserData(){
axios.get('api/members/getAllMembersData').then(response => {
this.members = response.data.data;
this.makePagination(response.data.meta, response.data.links);
});
},
Your response is still inside the axios get method, therefore the makePagination function has to be called inside axios method as well (inside .then())
getAllUserData(){
let $this=this;
axios.get('api/members/getAllMembersData').then(response=>
this.members=response.data.data
$this.makePagination(response.data.meta,response.data.links);
},
makePagination(meta,links){
let pagination={
current_page:meta.current_page,
last_page:meta.last_page,
next_page_url:links.next,
prev_page_url:links.prev
}
this.pagination = pagination;
}

VueJS/Laravel - vue-resource allways gives status 419 on post request

i'm trying to get my post request running in vue.
I'm using vue-resource to do post/get requests. Get method is working. Post is not.
I used the vue-resource "get" for a pagination on my laravel program and it worked perfect.
Now I need to pass some data via post to my server, but this doesn't really work.
My app.js:
// require('./bootstrap');
window.Vue = require('vue');
import VueResource from 'vue-resource';
Vue.use(VueResource);
Vue.component('example-component', require('./components/ExampleComponent.vue'));
Vue.component('prices', require('./components/prices.vue'));
const app = new Vue({
el: '#app'
});
The important part of my component, where i'm trying to do the post request:
saveSellAndBuy: function () {
Vue.http.post('/dashboard/savePricingData', {
buyAP: this.buyAP,
sellAP: this.sellAP,
tradeID: this.currentEditedKey
}).then(function (data) {
console.log(data);
});
}
What I get:
app.js:13790 POST http://unicorn.com/dashboard/savePricingData 419 (unknown status)
Some exceptions of laravel with no message
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "/var/www/unicorn.de/htdocs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
line: 203
message: ""
And yeah.. I have no clue anymore. Other people with the same or related problem said I need this in my head:
<meta name="csrf-token" content="{{ csrf_token() }}">
and this at the end ( this gets rendered after the vue instance )
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Of course I had those at the right place. I also tried to put this snipped here:
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');
At the end of my app.js file and it did not worked out for me. If I put this code over the const app and not at the end, my whole vueJS is not running anymore.
And here a picture that shows, that I do have the right cookies like XHR
Okay, I've found a way. I haven't thought that this will work. In the Laravel VerifyCsrfToken.php is a :
protected $except = [
'/dashboard/saveTradingData'
];
Where I can add URIs that should be excluded from CSRF verification.
But I don't really like this solution..
You can set the headers of any requests going out for vue-resource using interceptors:
Vue.http.interceptors.push((request, next) => {
const token = document.querySelector('#token').getAttribute('content')
if (token) {
request.headers.set('X-CSRF-TOKEN', token)
}
next()
})

Laravel VueJS axios interceptor accessing the vue application

I've got what's basically the default Vue JS scaffolding that comes with Laravel.
// app.js
require('./bootstrap');
window.Vue = require('vue');
const app = new Vue({
el: '#app',
methods: {
refreshToken: function() {
console.log('refreshing the token');
}
}
});
// bootstrap.js
window._ = require('lodash');
window.Popper = require('popper.js').default;
try {
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
This should be familiar to anyone who has used Vue JS with Laravel before.
Now i've tried to add an axios interceptor to handle errors, i've done this below the X-Requested-With header in bootstrap.js
window.axios.interceptors.response.use(
response => response,
error => {
// Show the user a 500 error
if (status >= 500) {
console.log({500:error});
}
// Handle Session Timeouts
if (status === 401) {
console.log({401:error});
app.refreshToken();
}
// Handle Forbidden
if (status === 403) {
console.log({403:error});
}
return Promise.reject(error)
}
);
The console.log() instances work fine to verify that it is working.
However app.refreshToken() does not work (and does not give an error either?).
I'm not that surprised since I haven't imported it or anything.
But i've tried this at the top of bootstrap.js: import app from './app.js';
And npm run watch now throws a warning:
"export 'default' (imported as 'app') was not found in './app.js'
I modified app.js to change const app to be export const app but this didn't make any difference.
I'm pretty sure I am just missing some basic understanding of importing and exporting within es6 but unfortunately I can't find anything on Google that will explain it.
Most of my Googling of how to setup this axios interceptor to handle errors has come up with examples using vuex. I really don't want to bring in vuex just to resolve this as I don't want to touch it until i'm sure it's necessary for my particular app and it definitely seems overkill just to be able to follow a tutorial.
How can I call my app.refreshToken() method or access my vue instance within the axios interceptor?
After
require('./bootstrap');
window.Vue = require('vue');
const app = new Vue({
el: '#app',
methods: {
refreshToken: function() {
console.log('refreshing the token');
}
}
});
Add what the error says it's missing:
"export 'default' (imported as 'app') was not found in './app.js'
Just add this:
export default app;
That might solve the compilation problem, as for the call to the function, i have not tested it yet... came with a very similar problem 15 minutes ago..

Make AJAX call in AngularJS in Cordova App

I have built an app using Ionic Framework, AngularJS, and Cordova. In it, I have made AJAX calls to several php files using $http.get(), which works perfectly in a browser, but not within the app. The app is able to render internet pages through an iframe so the network is working. I have whitelisted my server where the php files reside inside of the app.js file and using . Also, in my php files I've added header('Access-Control-Allow-Origin: *');
Any suggestions on how to get this AJAX call to work?
.controller('StuffCtrl', function($scope, StuffService, LoadingService) {
StuffService.getStuff().then(function(data) {
LoadingService.show();
$scope.stuff = data;
LoadingService.hide();
});
})
.service('StuffService', function($http){
var myStuff;
return {
getStuff: function(){
return $http.get('http://mydomain/stuff.php').then(function(items) {
myStuff = items.data; return myStuff;
});
}
});
});
I had the same error while working on a hybrid app and then I added these lines in my route config function and it started working
$httpProvider.defaults.useXDomain=true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
This is to enable CORS.
More info on the same can be found here
Add a catch handler to get the error :
StuffService.getStuff().then(function(data) {
LoadingService.show();
$scope.stuff = data;
LoadingService.hide();
}).catch(function(error){
$scope.error = error;
});
And pretty display the error :
<pre>{{error|json}}</pre>
This should tell you what is going on.

NodeJS unable to response.write to the browser when there is delay in callbacks

i'm using simple MVC structure by Nathan Broslawsky. i have these code below.
ArticleProviderDBController.prototype.Show = function(data) {
//Init Model
var res = this.Response;
var model = this.getModel();
var view = this.getView("ArticleProviderDB");
model.findAll(function(error, article_collections){
if( error ) console.log(error);
view.renderGH(res, data, article_collections); //this will actually call the renderGH function to serve a html file with data from DB but it is not working.
res.write('inside callback'); //this will not.
//res.end();
});
//console.log(_self.Response);
res.write('outside callback'); //this will be shown on my browser.
//res.end();
}
actually i try to follow what people have done using expressjs
app.get('/', function(req, res){
articleProvider.findAll( function(error,docs){
res.render('index.jade', {
locals: {
title: 'Blog',
articles:docs
}
});
})
});
but seems like it is not working.
i also saw a post NodeJS response.write not working within callback posted recently but his solution is not working for me. My main objective is to use simple MVC structure created with Nodejs without the use of other templates such as expressjs to serve html with DB query. thank you.

Resources