我正在使用 Axios
将我的数据从 Vue
发布到 Laravel Controller
。
我使用下面的代码来解决问题。但它不起作用!
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')
};
这是我想发布的方法:
onSubmit(event) {
event.preventDefault();
this.$http.post('store', {
email: this.email
}).then( (res) => {
console.log(res.data.newsletter_success)
}).catch( (err) => {
console.log(err);
})
}
有什么问题?? Laravel CSRF
文件中有一个 bootstrap.js
设置。
答案 0 :(得分:0)
嗯,这可能是由您代码中的前 2 行引起的:
import Axios from 'axios'
window.axios = require('axios');
您应该选择一种导入 axios 的方式并使用该方式
看看这个解决方案:
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')
};
现在我们确定 Vue.prototype.$http(即 window.axios)也会发送您设置的 CSRF 标头。
答案 1 :(得分:0)
你可以给 headers
喜欢 ajaxSetup
this.$http.post('store', { email: this.email},
{
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
}