How to fix ajax problem: 500 Internal Server Error in laravel? - ajax

I tried using ajax to fetch my data from database and display it in my blade without refreshing it but when I applied the same steps to fetch different data for the other blade i get this error :
POST http://localhost:8000/barangay/fetch 500 (Internal Server Error)
jquery-3.3.1.js:9600.
Here is the code that needs fixing:
This is my blade:
Here is my ajax script:
Here is my router to fetch the barangays that belonged to the selected city:
Here is my code in my controller to get the data:
and here in here is the output (error :returns nothing):

Laravel uses the CSRF token in post request, so you required to add header in your ajax request something like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
for more more details you can use https://laravel.com/docs/5.8/csrf

In addition to checking for the CSRF token as a POST parameter, the VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in an HTML meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
By default, the resources/js/bootstrap.js file registers the value
of the csrf-token meta tag with the Axios HTTP library. If you are
not using this library, you will need to manually configure this
behavior for your application.

Related

CSRF token mismatch when making a POST request with Axios

I have a route in api.php which I need to use 'web' middleware on to check for csrf verification because I don't want that route to be accessible from outside.
I have read the following solutions:
Laravel “CSRF token mismatch” for POST with laravel-cors and axios
CSRF Token mismatch, laravel and axios
Laravel + Vue.js (axios) - CSRF token mismatch
https://laracasts.com/discuss/channels/laravel/csrf-token-mismatch-6
All of the say the same - have <meta name="csrf-token" content="{{ csrf_token() }}"> in the document header and be sure to add this token to axios header in bootstrap.js after including axios. Here's my bootstrap.js fragment
window.axios = require('axios');
window.axios.defaults.headers.common = {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'X-Requested-With': 'XMLHttpRequest'
};
As you can see, everything seems to be setup correctly. I even tried assigning the token to axios header right before making the POST call but still the same issue persists - I keep getting "CSRF token mismatch". Any ideas what could be wrong?
EDIT: I have also tried appending "_token" with csrf token value in form body, still same issue.

CSRF Token Name on Django Documentation is not Matching the Actual Name of the Variable in AJAX Header

I was struggling to send and recieve CSRF token, and I found, in the end, that Django was not able to get the token value because its name was different from the recommended one in its documentation. Why?
(I am doing AJAX on a HTTPS address and requests are cross-site.)
Django documentation recommends that I add token to AJAX header in following way:
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Here, the name is X-CSRFToken, which somehow becomes HTTP_X_CSRFTOKEN.
On the other hand, Django is looking up the cookie under CSRF_COOKIE.
Line 278 in csrf.py of CsrfViewMiddleware:
csrf_token = request.META.get('CSRF_COOKIE')
if csrf_token is None:
# No CSRF cookie. For POST requests, we insist on a CSRF cookie,
# and in this way we can avoid all CSRF attacks, including login
# CSRF.
return self._reject(request, REASON_NO_CSRF_COOKIE)
I cannot change the variable name because I get this error:
Request header field CSRF_COOKIE is not allowed by Access-Control-Allow-Headers in preflight response.
So, I ended up changing the variable name in the source code from CSRF_COOKIE to HTTP_X_CSRFTOKEN. Are there any way to make this work?
(I do not do #csrf_exempt, so please do not recommend.)
The problem is not from Django, if you read closely here: https://docs.djangoproject.com/en/2.0/ref/csrf/#how-it-works you will understand how it works and what kind of logic they follow.
The problem is that you are not allowing the headers:
Request header field CSRF_COOKIE is not allowed by Access-Control-Allow-Headers in preflight response.
If you search for this ACAH you will find that you must edit your server config file to allow this kind of posts.
The other case is that you may not be sending properly the header and that's why it's looking for the cookie. In that case you can try adding this to your header:
xhr.setRequestHeader('X-CSRFToken': $('meta[name="token"]').attr('content') });

Laravel + Vue.js - CORS issue with specific address?

Laravel 5.6
Vue 2.5.7
Google Chrome
Hi, I am trying to understand this CORS issue, i'm still trying to find a way to consume this list: https://api.coinmarketcap.com/v2/listings/, and I receive the following error:
(index):1 Failed to load https://api.coinmarketcap.com/v2/listings/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://tours.mine' is therefore not allowed access.
yet if I goto this address: https://jsonplaceholder.typicode.com/posts/ everything works fine.
After using this Moesif Chrome CORS extension, and thus disabling CORS for chrome, I received a new error:
Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response. received only on this address: https://api.coinmarketcap.com/v2/listings/
http://tours.mine - is a local name I set in httpd/vhosts.conf.
I've tried BarryVdh cors lib, I also created my own CORS middleware, nada.
Flow:
in web.php routes:
Route::get('/', function () {
return view('welcome');
});
in welcome.blade I pass the csrf in both meta:
<meta name="csrf-token" content="{{ csrf_token() }}">
and script:
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
My Vue instance:
<div class="container" id="app">
<coin-add-component></coin-add-component>
</div>
and in my component I have the following hook:
mounted(){
this.axios.get('https://api.coinmarketcap.com/v2/listings/')
.then(response => {
console.log(response.data);
})
.catch(e => {
this.errors.push(e)
})
}
Your help is appreciated,
Bud
The url you are trying to consume can't be used in crossdomain with javascript because it doesn't provide a response header of type "Access-Control-Allow-Origin".
In this case, if you have no control on the API server you are forced to use other unconventional ways because all modern browsers will block any requests to that site if the domain doesn't match with yours.
You have 2 alternative to solve this problem:
Use a proxy with your same domain of yours to redirect all calls to that server
Make ajax calls to your server and then make your server communicate directly with the api server using for example curl
if you are using this(https://github.com/barryvdh/laravel-cors) make sure you turn off csrf token in your mid

Angular2 Http Laravel CSRF Token

Muddling through some Angular2 tutorials and trying to get a post request to work in Laravel 5.2 I have added this meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
but I'm not sure how to pass that in the headers section or honestly if that is where it should go.
let headers = new Headers({ 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '???????' });
Update: So I added a function to pull the csrf-token from the meta tag but still have not found a way to get it passed to the Laravel post request.
getToken() {
let token = document.querySelector('meta[property="csrf-token"]')['content'];
return token;
}
Thanks
This is what I did. Not sure if it is the best way but it worked.
In the main Laravel template I added this meta tag.
<meta property="csrf-token" name="csrf-token" content="{{ csrf_token() }}">
In the Angular2 whatever.service.ts I added a get token function.
getToken() {
let token = document.querySelector('meta[property="csrf-token"]')['content'];
return token;
}
In the same service I added this to the post method.
let headers = new Headers({ 'Content-Type': 'application/json', 'X-CSRF-TOKEN': this.getToken()});
Laravel now accepts the post without the 500 Token Mismatch Error
Please chime in if there is a better solution!!
This should be the same "problem" as with <title>{{ title() }}</title>: There's no component. This means: Angular won't/can't do any interpolation here. For the title tag the angular team provides an injectable Title service. For meta tags you've got to roll your own solution.
Have a look here: https://wijmo.com/blog/how-to-improve-seo-in-angularjs-applications/
They use document.querySelector to access the meta element and then setAttribute to manipulate its contents.

Encountering "TokenMismatchException in VerifyCsrfToken.php" error

I am attempting to perform an AJAX submission to Laravel. According to Laravel's documentation here, I need to add a CSRF token as both a request header and POST parameter. I'm retrieving the CSRF Token from the XSRF-TOKEN cookie as also described in the documentation:
// Grab XSRF cookie.
var csrf_token;
var cookies = document.cookie.split(';');
for(cookie_offset in cookies) {
var cookie_parts = cookies[cookie_offset].split('=');
if(cookie_parts[0].trim() === 'XSRF-TOKEN') {
csrf_token = cookie_parts[1].trim();
}
}
This retrieves a token similar to the following:
eyJpdiI6Ik96QTdtcFIzam85TGJNQ3pzNUF1blE9PSIsInZhbHVlIjoiQm8zelBSaFpaM0JZcjlxcURFVEZNenZWMzNxUHFBMm1VVzM3YXpBbjVvaTBReEY5cFA1RGV3UVBHQWhjVGhZYmtDZ2lacGxFejJwQkxHaGplV1wvVEtRPT0iLCJtYWMiOiI3NTlkZmI5ODU2YTdlN2RiYTA1YTAyM2NiZmZlOWUwZTQyY2I0NTUzOWEyNzI5YjE2ODIyMmU1YzZiNDE1MmQ0In0
Once I have the token, I am adding it as a X-CSRF-Token header and _token POST parameter.
When I perform the request, I'm receiving this error:
TokenMismatchException in VerifyCsrfToken.php line 46
I've also tried passing the token as a X-XSRF-TOKEN header instead, but am getting the same error
When I set the X-XSRF-TOKEN and omit the _token POST parameter, I encounter a different error:
DecryptException in Encrypter.php line 142:
Invalid data.
What is it that I am missing here?
UPDATE:
After some more debugging and comparing this request with requests being generated by an AngularJS implementation which ran side-by-side this implementation, I discovered the problem was that I needed to URL Decode the cookie's value.
I simply needed to do the following, after extracting the csrf token from the cookies:
csrf_token = decodeURIComponent(csrf_token );
You add the token to the client's request either for AJAX or as a hidden field in a form. You have to add a way for the client to know what the token is. One method is to use the token meta tag from the base view:
<meta name="xsrf-token" content="{{Session::token()}}" />
Then in your javascript side for any ajax request you can do:
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-Token':$('meta[name="xsrf-token"]).attr('content')
}
});
}
Otherwise when you post you can use the CSRF token in a hidden field
as so:
<input type="hidden" name="_token" value="{{Session::token()}}">

Resources