Laravel 5 ajax loop TokenMismatchException and cipher invalid - php

In my Laravel 5.2 application, I'm trying to post some URLs via ajax in a loop but I get problems with both:
No supported encrypter found. The cipher and / or key length are invalid.
and
TokenMismatchException
Javascript code:
urls.each(function(url) {
var data = {
urls: url.value
};
$.ajax({
type: "POST",
url: "/ajax/checkUrl",
data: data,
headers: {'X-CSRF-TOKEN': '{!! csrf_token() !!}'},
success: function (data) {
var result = $.parseJSON(data);
console.log(result['msg']);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Error: ' + thrownError);
}
});
});
routes.php
Route::group(['domain' => env('APP_URI')], function() {
Route::group(['middleware' => ['auth']], function () {
Route::post('ajax/checkUrl', 'AjaxController#checkUrl');
});
});
My AjaxController method is just following each URL with cURL, get some data and passing it back to the view.
Usually, I get the error
production.ERROR: exception 'RuntimeException' with message 'No supported encrypter found. The cipher and / or key length are invalid.' in C:\wamp\www\app\vendor\laravel\framework\src\Illuminate\Encryption\EncryptionServiceProvider.php:45
It works first but after ~50 ajax requests, some of them starts to fail with 500 (Internal Server Error).
I have tried with:
Excluded the ajax URL in VerifyCsrfToken Middleware.
Modified VerifyCsrfToken Middleware as some people at Stackoverflow suggested
Generated a new App key
In my config/app.php I have:
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
My code works fine standalone outside the Laravel application so I don't know why I get these errors, even if I exclude the URL from CSRF protection?
These errors occurs on localhost. The production server generates 401 Unauthorized after ~100 ajax requests and sometimes logs me out.
Any suggestions why this occurs?

Related

ajax from framework7 to laravel gives me unauthorized error

I've been trying to send ajax request to my laravel backend from my framework7 frontend using ajax.
$.ajax({
url: 'localhost:8000/server_file/grabtracks',
data: {task: "tracks"},
method: 'get',
async: false,
}).done(function(data) {
grabbedTracks = data;
});
Here is the code on my Laravel 5.4 routes
Route::get('/grabtracks', 'HomeController#grab_track');
And here is from my controller
public function grab_track()
{
$tracks = Track::all('id','title','location','price','track_file','track_img');
return response()->json($tracks);
}
I've disabled the CSRF tokens for the meantime, but i keep getting
Unauthorized error from my request
I'm at a loss, i've tried searching but only angularJS and laravel comes up.
It's probably your Controller has Auth middleware in your constructor remove the middleware and everything should work fine:
So you can remove this instructor or modify it to web auth:
public function __construct()
{
$this->middleware('auth');
}

DELETE and PUT does not recognize even after adjusting all required apache configurations

I have a Laravel app that I recently uploaded on the server.
From this Question I found that I should add these to end of htaccess file (after all laravel configurations) in public directory:
<Limit GET POST PUT DELETE>
Allow from all
</Limit>
But server can not recognize requests that sent via PUT or DELETE methods and shows this error :
501
Not Implemented
The requested method is not implemented by the server.
Apache version is 2.2.31 and operating system is linux.
What is problem and does remain something that I should be add?
Update:
This is a part of my routes related to issue:
Route::group(['prefix' => 'post'], function () {
Route::resource('/category', 'CategoryController');
});
In the other hand I used a $.delete user defined function like this to send DELETE requests:
$.delete = function (url, data, callback, type) {
if ($.isFunction(data)) {
type = type || callback,
callback = data,
data = {}
}
return $.ajax({
url: url,
type: 'DELETE',
success: callback,
data: data,
dataType: type
});
}
And I used it to delete a category by it's ID:
$.delete('http://mysite.ir/post/category/20'+ , {}, function (res) {
// console.log(res);
}, 'json');
And destroy method that delete selected category:
public function destroy ($id, Request $request)
{
Category::destroy($id);
return ['success' => true, 'msg' => 'category removed.'];
}
It might be something you also need to change in your apache config file?

Laravel Validation redirect after ajax call

I have a fresh 5.3 installation and want to make api calls with postman. I also tried it with angular2 to make sure it's not a problem with postman.
In my routes/api.php I got a simple route:
Route::post('test', function(\App\Http\Requests\LoginRequest $request) {
return $request->all();
});
LoginRequest is checking if the fields email and password are there. If so, the output is as excepted. But when it's missing it redirects to /.
Do I have to add some information for form validation for ajax calls? I thought laravel would return a json error object when there is an ajax call.
Update:
I found out that I missed the Accept application/json header in Postman. With it it works finde. But is there a way to say that all api/* calls should be treated as a json call?
I created a new parent class for my Requests. It checks if the route belongs to the api group or not. I tried to add a Middleware to the group to add the header, but this trick failed.
class JsonRequest extends FormRequest
{
public function expectsJson()
{
return ($this->route()->getAction()['middleware'] == 'api');
}
}
You can response to ajax call like this
return response()->json(array('error' => $validator->getMessageBag()->toArray()), 400);
response status 400 indicates error and you will get in error section
error: function(jqXHR, textStatus, errorThrown){
var errResponse = JSON.parse(jqXHR.responseText);
if (errResponse.error) {
$.each(errResponse.error, function(index, value)
{
console.log(value);
});
}
}

Laravel route not found but data saved in DB

I am using laravel 5 POST route in an AJAX call, I have defined it as,
Route::post('user/save-draft', ['as' => 'user/save-draft', 'uses' => 'UserController#saveDraft']);
I am also using Route::resource for the same controller above this save-draft route as,
Route::resource('user', 'UserController', ['except' => 'index']);
I am posting a form using AJAX with loading icon, what I am having strange here is that, data get save in the database, but I receive 404 error in the console like,
jquery.js:9664 POST http://www.example.com/user/save-draft 404 (Not Found)
So strange, and loading icon never get disappear which I do in ajax.done function.
While, my AJAX call is something like that,
var postData = {};
postData['frmSaveDraft'] = $frmSaveDraft.serialize();
startAjaxLoading()
$.ajax({
url: "http://www.example.com/user/save-draft",
type: "POST",
data: postData,
success: function (data) {
alert('success')
stopAjaxLoading();
}
});
UPDATE: Sorry, I missed url in AJAX here in above question,
Any thoughts ?
In controller method, I was returning response as,
echo json_encode(array('response' => true)); exit;
which was causing this issue may be exit keyword.
I have returned the response like,
return Response::json(array('response' => true));
which works great.

Laravel 5 making DELETE request by ajax - method not allowed

I'm trying to make a DELETE request within a Laravel app using ajax
I have a function to make the request - using the right verb - to a resource but keeps coming up method not allowed:
Here's my ajax request:
$.ajax({
type: 'DELETE',
url:'/user/58',
data: {
'_method': 'DELETE',
'id': id
},
dataType: 'json',
success: function (data) {
// do something with ajax data
if (data.result) {
return true;
}
return false;
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('error...', xhr);
return false;
//error logging
},
complete: function () {
//afer ajax call is completed
}
});
id is supplied within a function and for the test is 58.
Watching the network panel in Chrome I can see it starts with the expected url of user/58 but then quickly gets shortened to user
I know that to get the resource route to pick up the request it needs to be user/58 and the method DELETE so it will go to the destroy method and because of this it is being routed to the Index method which expects a GET request hence the method not allowed.
Why is my request url being changed?
What is the correct approach to make a DELETE request in Laravel?
Thanks
Edit:
Here's my route:
Route::group( [ 'middleware' => [ 'auth' , 'admin' ] ] , function ()
{
Route::resource( 'user' , 'UserController' );
} );
The csrf token is being taken care of in the headers - fairly certain this isn't the cause of problem as I do not get an invalid token exception
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Thanks
Two possible things that can happen here, I need to write this in a longer post than a comment so hopefully I got it right.
First thing that pops in my mind is an auth check that fails while doing the ajax request. At least I would redirect you back to the main resource if you wouldn't have enough rights.
However, my second guess is maybe even more likely. Have you thought of the X-CSRF-TOKEN that you need to send with an ajax request? See https://laravel.com/docs/5.2/routing#csrf-x-csrf-token
From the docs:
In addition to checking for the CSRF token as a POST parameter, the Laravel VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a "meta" tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
Once you have created the meta tag, you can instruct a library like jQuery to 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')
}
});

Categories