Laravel+vue (axios) 上传图片时报错:CSRF token mismatch.
感谢大家关注这个问题!
一开始这个报错,经过百度后用了这个方法:
1、在index.html的head中添加
<meta name="csrf-token" content="{{ csrf_token() }}" />
2、js:
let config = {
headers:{
'Content-Type':'application/json;charset=UTF-8',
'X-CSRF-TOKEN':document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'X-Requested-With': 'XMLHttpRequest'
}
};
axios.post('/api/upload_avatar',{data:img},config)
.then(response=>{
that.avatar = 'http://***.com/api/'+response.data;
});
还是报错:CSRF token mismatch.
打印了一下
document.querySelector('meta[name="csrf-token"]').getAttribute('content')
发现结果直接就是字符串{{ csrf_token() }}
{{ csrf_token() }}
这个是 blade 模板语法,你这个是 index.html,行不通的axios
默认会从 cookie 中读取XSRF-TOKEN
值,设置X-XSRF-TOKEN
header。