laravel - Laravel 和 Vuejs 中的 CSRF 令牌不匹配
问题描述
我正在使用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);
})
}
问题是什么??CSRF
Laravelbootstrap.js
文件中有一个设置。
解决方案
那么它可能是由您的代码中的前两行引起的:
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 标头。
推荐阅读
- javascript - 在 discord.js 中获取此套接字错误并且无法调试它
- c - return 从指针目标类型中丢弃“const”限定符
- selenium - 尝试导入 Cucumber 时 Cucumber + Selenium 出错
- r - 绘制逻辑值的密度
- machine-learning - 我可以使用什么机器学习方法来识别颜色?
- python - 站点地图生成:手动更新页面的 lastmod/last_published_at
- c# - xamarin Essentials:没有重载>'OnMainDisplayInfoChanged'匹配委托>'EventHandler
' - c# - 如何在 rad 向导步骤更改上触发 ajax 请求
- r - R scale() 打印 .Rmd 文件输出中的所有数据集
- excel - Python中的数据对齐