Good day, I'm having trouble on sending post data to my Laravel project, It always shows Page Expired (419) on this,
Error 419 on POST
Here's the things I have done before coming up to my question:
Added SESSION_SECURE_COOKIE=FALSE on .env
Changed the config/session.php from 'secure' => env('SESSION_SECURE_COOKIE'), to 'secure' => env('SESSION_SECURE_COOKIE', false),
Added ob_start(); at the beginning of public/index.php like this <?php ob_start(); use Illuminate\Contracts\Http\Kernel; use Illuminate\Http\Request;
This is my route
Route::post('/data', [AdminController::class, 'getSensorData']);
Also in I'm sending the data to the database from the post request using the controller.
The request works fine when the method is GET.
200ok on GET
Edit: It's working now, the fix was from #Ahmed Hassan. Thank you.
this issue occur because you didn't send the CSRF token with the request
just add #csrf inside your form and it will work
also, you can exclude your URL in the $except list in the App\Http\Middleware\VerifyCsrfToken
I hope it's helpful
Related
I'm working on a project with Laravel and inline vue*. For submitting forms we use axios-calls.
On chrome there is no issue, but in Firefox, with every axios call it gives back a 419 error 'csrf tokens mismatched'.
I googled this issue, and some say adding the CSRF-token to the header. Did that, see below, but it does not work.
axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'X-XSRF-TOKEN': decodeURIComponent(this.readCookie('XSRF-TOKEN')),
};
After trying lot's of different answers, I added '*' to the $except array in VerifyCsrfToken.php. (= All my routes will not work with the CSFR-token, not a good practice, but i did this for debug)
The form will submit now. But in the form handling (controller.php), I save some data in the session. In chrome I get the data I need, in Firefox this session data is null.. So I guess the csrf-token stored in the user session is null in firefox. How do I fix this? How do I solve the issue with user-sessions?I also found out that when i send a request with firefox it creates an entire new session/file in storage/framework/sessions, always with a different _token..
I use this in myController.php, to store the data I need in the session:
$request->session()->put('formData', json_encode($data));
$request->session()->save();
TIA!
In .env
App_url=www.site.be
session_domain=
App_name=site
In session.php:
driver => file
lifetime => 120
encrypt => false
secure => false
'http_only' => true
*: We use inline vue-scripts in the blade.php files to submit data.
I tried:
CSRF-token to the header
$req->session()->save()
Changed .env variables around, and in session.php (values above are current)
Changed app_name so it will not have a '.' or '_'
Added _token="{{ csrf_token() }}" to formdata in axios call.
Added "content-type": "application/json" to axios call
Php artisan optimize:clear
Checked permissions on server
I expected it to make the site work, but alas, it does not.
Asked this question on r/laravel and it is solved.
It looks like Firefox isn't sending the session cookie, wich will
cause all the problems you described as a result. Use the browser
developer tools to inspect requests to confirm this. Then, try to
configure Axios to always send cookies, something like
withCredentials: true.
So I added "axios.defaults.withCredentials = true;". And it works! Will keep this here, so others might learn from my mistakes
Locally project runs fine. On the server getting this error while sending POST request to the POST route in Laravel 9 API.
"message": "The GET method is not supported for this route. Supported methods: POST."
My route from the api.php routes file:
Route::post('/userdata/create', [UserDataController::class, 'createAccount']);
My route from the routes list (from php artisan route:list):
POST api/v1/userdata/create .......... Api\V1\UserDataController#createAccount
Tried:
php artisan cache:clear
php artisan route:cache
php artisan route:clear
Didn't fixed it yet.
It happens cause you have forced your domain to HTTPS redirect and you are trying to use it as HTTP.
Your domain settings redirect your request to HTTPS but not to POST method.
If you look for postman logs/console you will find redirection of HTTP POST request to HTTPS GET request
Hence Error response by your server of
The solution to that problem was actually very simple:
I needed to send POST request to "https" url, and i was sending it to "http" url.
Still strange that server was complaining that GET method is used...
This problem happened to me recently where I was using .com instead of .net
that happen because laravel cannot return the error.
SOLUTION 1 :
you can use this inside your API post function :
try{
// example we have name field
$request->validate([
'name' => ['required','string','max:255']
]);
User::create([
'name' => $request->name
]);
return 'registered';
}catch(Exception $error){
// your error from validation will appear here
// dd($error->validator->messages());
}
SOLUTION 2 :
as alternative :
I found another method here at this link
I'm trying to get data from a database through this ajax request:
axios.get('/about-info')
web.php:
Route::get('/about-info', [CMSController::class, 'aboutInfo']);
CMSController.php:
public function aboutInfo()
{
$data = DB::table('about_info')->first('order by id desc');
return $data;
}
but instead I am getting the whole welcome.blade.php content. It looks like the url in web.php is not called and instead a redirect happens. The dev tools network tab shows a 302 redirect.
This thread seems to have insight on this issue. I've been trying to implement answer 3 (adding accept: 'application/json to the config/headers object of the request) but the object already has that entry:
config:
headers:
Accept: "application/json, text/plain, */*"
This guide is talking about auth middleware being the possible cause of this problem but I'm not using middleware (at least none I am aware of). Any idea how to get to the root of this?
Have you tried moving the route to your api routes file? All routes in the web namespace receive session state, CSFR, and possibly more that could be getting in the way (i.e. "new session, go to the welcome screen!").
This would change your URL path to:
axios.get('/api/about-info')
Turns out that web.php was not working at all because of caching issues. Running:
php artisan route:clear
made it work again and showed every problem, which could not be detected before clearing the cache.
I follow the Laravel official document step by step.
When I send a request to {{host}}/api/login, I can receive the response that includes the token. Everything is correct.
But when I try to send a request to {{host}}/api/user, it is always unauthenticated.
I checked my code several times, I cannot fix it.
In my .env file, I set as following, my backend host is http://laravel_8_api.test
SESSION_DOMAIN=.laravel_8_api.test
SANCTUM_STATEFUL_DOMAINS=.laravel_8_api.test
How can I make it work? Please help me.
The code is in this link https://github.com/ramseyjiang/laravel_8_api
Try this if you haven't
The reason this isn't working is that Sanctum is denying the authenticated request based on the referrer.
Add Referer to the request header in postman.
//api.php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
middleware should be auth:sanctum instead of auth:api
In the official document, it forgets to modify the config/auth.php
'api' => [
'driver' => 'sanctum',
'provider' => 'users',
'hash' => false,
],
After that, it will fix this issue.
Don't need to modify code in the code in the api.php
I mean it doesn't need to change auth:sanctum to the auth:api, if change it, it will make another issue as the link Laravel Sanctum : column not found: 1054 Unknown column 'api_token' in 'where clause'
Try this solution, may it will help you.(It helped me)
first you check is that your bearer token which you sending in header is really reaching to your app server?
Lets check it:
put this code in your route/api.php file
print_r($_REQUEST);
print_r($_SERVER);
exit;
now lets send postman request,
in response you will get a line like this
"[REDIRECT_HTTP_AUTHORIZATION] => Bearer 6|4rxthBID7kiSleFglD30aphZu3poiDYJjWMJgZZc"
if this line is missing then its mean your .htaccess file is not allowing to pass token to server.
So the solution is very easy, just add this line to your .htaccess file
#Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
I'm working with Laravel 6, and my session driver is file. I've faced a 419|page expired when I submit a form with post action and after tracing the codes I found out the session will restart after submission. Everything is good on local but on the server I've got this issue.
I tried with a raw Laravel project and it worked!
I've already checked directory permission, config/session.php,.env file.
.env
SESSION_DRIVER=file
SESSION_LIFETIME=120
config/session.php
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false
Tnx for responding.
the problem is not because of CSRF token, it's session's fault. evry time a new session and new token will be started so the token thet I send from input will be checked with another token !!!
If your form is in a blade, after starting the <form>, add a csrf field by putting #csrf.
If you're sending the POST request from somewhere else (i.e. from some other domain/subdomain that is not project domain) you may want to disable CSRF check by adding it in VerifyCsrfToken.php (\app\Http\Middleware\VerifyCsrfToken.php) like this:
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
// Place your URIs here
];
}