Reputation: 1636
In my laravel 5.3 application I have enable CSRF checking globally for all ajax requests.
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
But I have an ajax GET request for an external api as follows.
$.ajax({
url: "https://api.xxxxxxxxxxx/v1/" +code+ "?api_key="+API_KEY,
type: "GET",
dataType: "text",
success: function (data) {
},
error: function (msg) {
}
});
I need to avoid CSRF checking here. I have tried two ways but nothing works for me. In VerifyCsrfToken.php
1st way
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
'https://api.xxxxxxxxx/v1/*'
];
}
2nd way
class VerifyCsrfToken extends BaseVerifier
{
if ( ! $request->is('https://api.xxxxxxxxx/v1/*'))
{
return parent::handle($request, $next);
}
return $next($request);
}
Please figure it out, how to solve this issue.
Upvotes: 0
Views: 643
Reputation: 1636
Finally, I figured out a way within javascript
. We can delete the particular header before ajax
call, then reassign the header again.
delete $.ajaxSettings.headers["X-CSRF-Token"];
$.ajax({
url: "https://api.xxxxxxxxxxx/v1/" +code+ "?api_key="+API_KEY,
type: "GET",
dataType: "text",
success: function (data) {
},
error: function (msg) {
}
});
$.ajaxSettings.headers["X-CSRF-Token"] = $('meta[name=_token]').attr('content');
Upvotes: 1
Reputation: 606
This should help
$.ajax({
type:'GET',
url:"https://api.xxxxxxxxxxx/v1/" +code+ "?api_key="+API_KEY,
data:{_token: "{{ csrf_token() }}",
},
success: function( msg ) {
}
});
Upvotes: 0
Reputation: 2553
You can override the ajaxSetup
in that ajax
call like this.
$.ajax({
url: "https://api.xxxxxxxxxxx/v1/" +code+ "?api_key="+API_KEY,
type: "GET",
dataType: "text",
headers : {},
success: function (data) {
},
error: function (msg) {
}
});
Although, you shouldn't use ajaxSetup
.
The settings specified here will affect all calls to $.ajax or Ajax-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so. : https://api.jquery.com/jquery.ajaxsetup/
Upvotes: 0