yoyoma
yoyoma

Reputation: 3536

laravel out of box vuejs example not working

I'm simply trying to learn vuejs with laravel and cannot get the example component working.

I have created a fresh route to simply serve the vue example for now.

create.blade.php

<!DOCTYPE html>
<html>
<head>
<title>VUE</title>
</head>

<body>

<h1>example</h1>

<div id="app">

<example></example>

</div>

<script src="/js/app.js"></script>
</body>
</html>

The app.js and example.vue files are exactly as out of the box ( so i won't bother showing example.vue here

require('./bootstrap');

window.Vue = require('vue');

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#app'
});

I have npm run watch running and it seems to have built the app files ok.

Controller and route is fine, as page is loading, but I'm getting console error as follows

app.js:1697 Uncaught TypeError: Cannot read property 'csrfToken' of 
undefined
at Object.<anonymous> (app.js:1697)
at __webpack_require__ (app.js:20)
at Object.<anonymous> (app.js:778)
at __webpack_require__ (app.js:20)
at Object.<anonymous> (app.js:41430)
at __webpack_require__ (app.js:20)
at app.js:66
at app.js:69

When i click the console error in chrome it points to the line in app.js:

window.axios.defaults.headers.common['X-CSRF-TOKEN'] = 
window.Laravel.csrfToken;

Is it complaining about csrftoken because I've used it as a blade template ? How can I get it working inside laravel, just so i can play with and learn vuejs ?

Upvotes: 1

Views: 1600

Answers (2)

omarjebari
omarjebari

Reputation: 5499

I think it's better to modify your bootstrap.js file (after axios import line) with the following:

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
    'X-Requested-With': 'XMLHttpRequest'
};

Upvotes: 0

dispake
dispake

Reputation: 3329

The code that it is complaining about is in the resources/assets/js/bootstrap.js source, which you'll see is being referenced at the top of the app.js file. In your blade file, before you include your app.js, you can set the csrf token value.

<script>
    window.Laravel.csrfToken = {{ csrf_token() }};
</script>
<script src="/js/app.js"></script>

Or, alternatively, if all you want to do is play with the example as-is, you can probably just remove that line of code from bootstrap.js. But you'll probably need it later once you start using VueJS more.

Upvotes: 2

Related Questions