Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

vue.js - CSRF token mismatch in Laravel and Vuejs

I am using Axios to Post my data from Vue to Laravel Controller.

I have used this below code to resolve the problem. But it's not working!

import Axios from 'axios'
window.axios = require('axios');
Vue.prototype.$http = Axios;

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

This is my Method which I want to Post:

onSubmit(event) {
  event.preventDefault();

  this.$http.post('store', {
     email: this.email
  }).then( (res) => {
     console.log(res.data.newsletter_success)
  }).catch( (err) => {
     console.log(err);
  })
}

What is the problem?? There is a CSRF setup in Laravel bootstrap.js file.

question from:https://stackoverflow.com/questions/65642936/csrf-token-mismatch-in-laravel-and-vuejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well it may be caused by the first 2 lines in your code:

import Axios from 'axios'
window.axios = require('axios');

You should choose one way of importing axios and go with that

Have a look at this solution:

window.axios = require('axios');
Vue.prototype.$http = window.axios

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

Now we know for sure that Vue.prototype.$http (which is window.axios) will also send the CSRF headers you set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...