Uncaught ReferenceError: axios is not defined in Vue.js - laravel

I am creating a SPA application with reference to the following tutorial.
http://voerro.com/en/tutorials/r/building-spas-with-laravel-5-and-vuejs-2/1
Until yesterday The top page displayed without error.
But, Today I started virtual machine again and accessed it,
The following javascript error occurs.
Uncaught ReferenceError: axios is not defined
at new Auth (app.js:53626)
at Module../resources/js/app.js (app.js:53554)
at __webpack_require__ (app.js:20)
at Object.0 (app.js:54214)
at __webpack_require__ (app.js:20)
at app.js:84
at app.js:87
I tried to review Git's log, but there was not a history that changed.
Do you know how to resolve this??
class Auth {
constructor () {
this.token = window.localStorage.getItem('token');
let userData = window.localStorage.getItem('user');
this.user = userData ? JSON.parse(userData) : null;
if (this.token) {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + this.token; // <-this is the error point
}
}
....
export default Auth;
app.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Auth from './auth.js'
import Api from './api.js';
window.api = new Api();
window.auth = new Auth();
Vue.use(VueRouter);
bootstrap.js
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] =
'XMLHttpRequest';

Either use window.axios or import axios from 'axios' or vue.prototype.$axios = axios. It's a scoping issue. Don't rely on globals.

I realized the problem was caused due to commenting out or removing
require('./bootstrap'); /****in app.js ***/
That is if you are working with Vue in Laravel.
Note: This is not twitter Bootstrap for UI

Related

Deployed Laravel sanctum application not working anymore

I use sanctum for my vue Axios operations. I deploy to my shared hosting and I get this error in the chrome console:
GET http://foo.xyz/city 401 (Unauthorized)
bootstrap.js :
window._ = require('lodash');
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios.defaults.withCredentials = true;
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
Axios Get :
getCity() {
axios.get('/api/city')
.then((response) => {
this.cities= response.data;
})
.catch(function (error) {
console.log(error);
});
},
Everything is working in my localhost when I deployed this project into my shared hosting nothing worked, so how I can run this in my shared hosting?
I added the following code to the .env
SANCTUM_STATEFUL_DOMAINS="foo.xyz"
and problem solved.
PS:
foo.xyz is not the actual domain, I gave a different domain for security reasons.

Vue router.push() shows 404 component except browser is reloaded manually

With Laravel api resources, I have returned a desired path which I intend a user be redirected to once a record is successfully created.
The challenge now is that although it routes properly with Vuefrontend from the address bar on the browser, it loads the wrong component of 404 until I hit the refresh button on the browser. Is there a better way of fixing this without using window.location='path'?
Currently on my router file, I have the following.
import Vue from 'vue';
import VueRouter from 'vue-router';
import viewAsset from "./components/views/assets/viewAsset";
import NotFound from "./components/NotFound";
Vue.use(VueRouter);
export default new VueRouter({
routes: [
{ path: '/asset/:id/details', component: viewAsset, meta: {title: 'Asset Details ' }
},
],
mode: 'history'
})
And i'm using this.$router.push(response.data.links.self ); for the routing, where response.data.links.self is the path returned from the api

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()
})

How to connect the frontend library to laravel?

how to properly connect third-party plug-ins when developing on laravel?
I need the fullpage.js library
downloaded it via npm
in the resources/js/bootstrap.js file I added require ('fullpage.js');
In the resources/js/app.js file I added
$ (document) .ready (function () {
    $ ('. js-fullpage'). fullpage ({});
});
I launch the project and I see in the console
app.js: 4655 jQuery.Deferred exception: $ (...). fullpage is not a function TypeError: $ (...). fullpage is not a function
    at HTMLDocument. <anonymous> (http: // localhost: 3000 / js / app.js: 770: 21)
    at mightThrow (http: // localhost: 3000 / js / app.js: 4371: 29)
    at process (http: // localhost: 3000 / js / app.js: 4439: 12) undefined
app.js: 770 Uncaught TypeError: $ (...). fullpage is not a function
as if it does not see the connection it's a library ..
and generally my call code from resources/js/app.js is why you are ABOVE than resources/js/bootstrap.js, although they are connected in a different order
my bootstrap file
try {
window.$ = window.jQuery = require('jquery');
} 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');
}
require('fullpage.js');
Can you try to include it like
require('fullpage')
or you can try to pass full path
Add it to your webpack.mix.js and run npm run dev or npm run prod depending on your environment:
mix.js([
'resources/assets/js/app.js',
'path/to/fullpage.js',
], 'public/js/app.js')

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

Resources