[英]Can i Use Axios on a non SPA project?
I am feed up with ajax long style of sending request, I have used axios on an SPA project and its pretty cool, I checked on thee documentation to see how it works and works great, however if I try to make a request it tows an error of unauthenticated, i am using Laravel php framework as my code back-end, if I try to run this directly on ajax, it works, or on a normal form it works also. 我已经厌倦了ajax较长的发送请求样式,我在SPA项目上使用了axios,它非常酷,我查看了您的文档以查看其工作原理和效果,但是,如果我尝试发出请求,它会拖一个未经身份验证的错误,我使用Laravel php框架作为我的代码后端,如果我尝试直接在ajax上运行它,则可以正常运行,或者以正常形式运行。
Plus i don't have any authentication middle setup anywhere. 另外,我在任何地方都没有任何身份验证中间设置。
Here is a documentation to the library Axios Library 这是库Axios库的文档
Here is my Sample code 这是我的示例代码
axios.get('/home', {} , {
'X-CSRF-TOKEN' : "{{csrf_token()}}",
'X-Requested-With': 'XMLHttpRequest',
'Accept' : 'application/json',
'Content-Type' : 'application/x-www-form-urlencoded',
})
.then(function(ressponse){
console.log(success);
})
.catch(function(error){
console.log(error)
})
});
I a only returning all the request in my controller and not special 我只返回控制器中的所有请求,并不特殊
So my Question is, is it a problem with axios, or laravel, or i can not just use axios without any SPA framework (eg react, vue etc.). 所以我的问题是,axios或laravel是否存在问题,或者我不能在没有任何SPA框架(例如react,vue等)的情况下仅使用axios。
Thank you. 谢谢。
It's unauthenticated because you aren't setting X-CSRF-TOKEN
in the headers. 由于您未在标头中设置
X-CSRF-TOKEN
,因此未经身份验证。
You are setting a X-CSRF-TOKEN
property on the config object, but that is meaningless. 您正在配置对象上设置
X-CSRF-TOKEN
属性,但这是没有意义的。
axios.get('/home', {} , {
headers: {
'X-CSRF-TOKEN' : "{{csrf_token()}}",
// X-Requested-With is an ugly hack and you should use an Accept header instead of this (not as well as!)
'X-Requested-With': 'XMLHttpRequest',
'Accept' : 'application/json',
// You're making a GET request. There is no request body to describe the content-type of.
// 'Content-Type' : 'application/x-www-form-urlencoded',
}
})
if your axios config is in js file then you have to do below steps 如果您的axios配置位于js文件中,则必须执行以下步骤
1- you have to put this meta in your page layout header 1-您必须将此meta放在页面布局标题中
<meta name="csrf-token" content="{{ csrf_token() }}">
2- and change 2-并更改
'X-CSRF-TOKEN' : "{{csrf_token()}}",
to 至
'X-CSRF-TOKEN' :document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
in your js file 在你的js文件中
and test it, if it works then your problem was because of js file is not a blade file so {{csrf_token()}} in your axios config will not rendered by laravel to csrf token 并测试它是否有效,那么您的问题是因为js文件不是刀片文件,因此laravel无法将axios配置中的{{csrf_token()}}呈现给csrf令牌
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.