Level 3
Lumen is stateless. You must tokens to authenticate your requests. Use passport or the token driver
1 like
I am using Lumen 8.2.3.
i am trying to submit form with ajax.
i am trying to send token and i have error *Call to undefined function csrf_token()*
i added this in app.php:
$app->routeMiddleware([
'csrf' => 'Laravel\Lumen\Http\Middleware\VerifyCsrfToken'
]);
$app->middleware([
Illuminate\Cookie\Middleware\EncryptCookies::class,
Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
Illuminate\Session\Middleware\StartSession::class,
Illuminate\View\Middleware\ShareErrorsFromSession::class,
Illuminate\Session\Middleware\StartSession::class,
App\Http\Middleware\VerifyCsrfToken::class
]);
Also i tried with session to get token
<meta name="csrf-token" content="{{ app('request')->session()->get('_token') }}">
It is working but on the second ajax post request trows CSRF Token Mismatch
MyView with Ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<meta name="csrf-token" content="{{ app('request')->session()->get('_token') }}">
<title>Document</title>
</head>
<body>
<form action="/test" method="post">
<input type="text" class="form_element" id="name" name="test">
<input type="text" class="form_element" id="email" name="email">
<input type="text" class="form_element" id="product" name="product">
<input type="text" class="form_element" id="price" name="price">
<button type="button" class="kita">Posalji</button>
</form>
<script>
$(".form_element").on("focusout", function(){
let do_query = true;
setTimeout(function(){
$(".form_element").each(function(){
if($(this).is(":focus")){
do_query = false;
return false;
}
});
if(do_query){
let getallyourvalshere = $('#name').val();
let email = $('#email').val();
let product = $('#product').val();
let price = $('#price').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: 'post',
url: '/testAjax',
data: {
value: getallyourvalshere,
email: email,
product: product,
price: price
},
success: function(response) {
console.log(response);
},
error: function(xhr) {
console.log(xhr);
}
});
}
}, 200);
});
</script>
</body>
</html>
Thanks for help
Lumen is stateless. You must tokens to authenticate your requests. Use passport or the token driver
Please or to participate in this conversation.