The server responded with a status of 400 () Laravel and Vue js? - json

This is very strange, I'm building an SPA with Laravel and Vue js. I'm using Laravel Passport and JWT for Authentication. All of a sudden my Validation errors aren't displaying when I submit any of my forms. I keep getting this error:
Failed to load resource: the server responded with a status of 400 ()
If you fill in the Forms and click submit everything still works in the application, I see the success message and the data gets saved in the database. I have no idea what is causing this, at first I thought it had to do with the Recaptcha code that I implemented but now, I'm not 100% sure that that's the problem, since I removed all of the related code and tried to submit my forms again and still got a 400 error.
I know these details are pretty vague, but if anyone has idea what this could be related to it would be greatly appreciated.
Thank you.

You need to return a JSON error handle if you are using an API call.
The Laravel default error handling for validation is to throw Exception thru the blade that you can access as $errors
If you want to make your own validation use the validator facade.
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
public function store(Request $request) {
$validation = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required',
'password' => 'required',
]);
if($validation->fails()) {
return response()->json([
'status' => 'failed',
'message' => $validation->errors(),
], 400);
}
}

Thank you to those who commented or answered. I did actually figure it out. I added a couple of functions into my Exceptions/Handler.php file. I built this SPA based off of a Free Youtube Course and I grabbed the code that I placed in the Handler.php file after following a different paid course on Udemy. I didn't think these functions would cause any harm but they did. After removing them, everything is working great and back to normal. Thank you.

Related

Failing to include using Entity Framework and LINQ

I'm trying to get the latest forum threads in my forum, just like this:
var threads = _context.Threads.Include(x => x.User).OrderByDescending(x => x.CreateDate).Take(3).ToList();
However, this gives me the following exception:
There is already an open DataReader associated with this Connection which must be closed first.
Before I load these threads, I am loading some settings, like this:
var frontPageSettings = _context.Settings.FirstOrDefault(x => x.Key == Constants.SettingsKeys.FrontPageSettings.ToString());
Could this be the issue?
I have absolutely no idea what is happening, or how to get around it. Any guidance towards a solution is highly appreciated.
If you need more information such as stack trace, please let me know.
EXTRA INFO
I'm using Entity Framework for MariaDB (MySQL) and ASP.NET Core
EDIT
If I remove my .Include(x => x.User), the exception disappears, so I believe this has something to do with the include

How to get more specific errors, Ember Data 422 Error

I am attempting a post action using Ember-Data, and getting the following error which seems pretty common:
Error: The adapter rejected the commit because it was invalid
Problem is, seems like usually this returns more specific errors; I am only seeing the above message and a generic 422 error from the browser.
Does anyone know what I can do to access any specific error messages that might be thrown?
Potentially relevant info:
Using jsonapify on an express server to write to MongoDB
router.post('/',
jsonapify.create('info'),
logger.logErrors(), jsonapify.errorHandler()
);
I would expect the following code to log some sort of response but I am never able to see the message in this console.log:
info.save().then((response)=> {
console.log(`Server responded with ${response}`);
});
Sorry for the vagueness here, I'm sure there could be all sorts of problems with my models and whatnot, but I want to know what I can do to find the more specific errors if they exist.
Thanks much and plz lmk if I can update with more info.
.then() takes two arguments, like so: .then(success, failure) the first one being a function to be called on success, and the second to be called on failure. A 422 response is a failure, and your current code only has a success handler, so it will never be called. Basically, copy-paste your current success handler to be the second argument to your .then() call.
Also, generally in your browser you can open up the inspector and take a look at the request in the 'network' tab.
Your new debugging code could look something like this:
let success = (response) => {
console.log(`Server responded with ${response}`);
};
let failure = (response) => {
debugger;
};
info.save().then(success, failure);
Then you should be able to poke around the response object in your js console and see what's going wrong.

Why get Unable to verify your data submission error in Yii2?

Error:
Unable to verify your data submission error
Create one public function in Yii2. But, submit data not accept in this method,
see following error images. Why is this happen?
If you create the form manually (i.e. without using the yii form methods), you should add an input field like this:
<input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" />
source: http://zero-exception.blogspot.com/2015/01/yii2-using-csrf-token.html
Add this in the head section of your layout: <?= Html::csrfMetaTags() ?>
There are various solutions to this problem, I guess understanding why it happened in the first place helps solve the problem.
It is either caused by an invalid csrf token,user generated csrf token, expired csrf token, all these 'csrf' issues will arise when you have custom forms built not using the 'ActiveForm' class.
If CSRF is not the issue,
Its other cause occurs when you try to upload multiple files and the web server cannot handle the load. Some properties to check on this to make sure you are on the right track is to claculate the size of files one is attempting to upload and check the web server's post_max_size and upload_max_filesize
If you are running linux, check php.ini file for inputs like these:
; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size = 8M
; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads = On
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2M
Based on your calculations, adjust the above php.ini parameters to suite your needs, then test.
I had a similar problem and I solved it.
To permanently disable csrf validation in whole application add below code in your configurations.
$config = [
'components' => [
'request' => [
'enableCsrfValidation' => false,
],
],
];
Also sometimes you can get this error using Yii 2.0 due to the post_max_size, upload_max_filesize, max_input_time also too maybe the webserver can be trimming the post so verify on nginx - client_max_body_size or in apache - LimitRequestBody
Disable for only specific action
/**
* #inheritdoc
*/
public function beforeAction($action)
{
if ($action->id == 'my-action') {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
Check whether there is hidden input in your form with CSRF token. It should look like
<input type="hidden" name="_csrf" value="ZEZ6Y0xrY3ARGS42fTwhMQgkDgF6BCEGEx4SMXQMBR4CPy0iPCIwNQ==">
A long story has been discussed here github
So disabling csrf somehow unsure for ajax request. I have met this issue many times.
So remember to send _csrf key when you send data by POST via ajax.
Updated from yii 2.0.12 to 2.0.30
Have this bad request error 400
Got the Html::csrfMetaTags() in the header layout.
using activeform,therefore is not caused by missing csrf token in the
form. And checked already through inspect.
I solved this through adding below code to the backend/config/main.php.
'components' => [
'request' => [
'csrfParam' => '_backend_csrf',
],
Is it a correct way or will it cause security issue?
A little differentiation to dchakarov's answer due to Yii2 tiers using instead of
_csrf variable _frontendCsrf.
<input type="hidden" name="_frontendCsrf" value="<?=Yii::$app->request->getCsrfToken()?>" />
This is a second time this question did not help me even though I posted a comment previously, so I have to post a response.
$csrf = \yii::$app->request->csrfParam;
$token = \yii::$app->request->csrfToken;
//start from
echo Html::hiddenInput($csrf,$token);
//end from
Switched website form https to http and had the issue come up. Updated the request config by commenting the below lines to resolve.
'request' => [
'cookieValidationKey' => 'SomeRandomKeyValidationString',
//'csrfCookie' => [
// 'httpOnly' => true,
// 'secure' => true,
//],
Add this in your controller:
public $enableCsrfValidation = false;

After uploading Laravel to server I get an error message on my routes page

I'm almost done with a Laravel project I'm working on and am wanting to try it out on an actual server.
However after I loaded the entire project (slower than using composer but I was hoping to keep this as simple as possible the first time I tried this) I can't even log in as I'm getting a "syntax error, unexpected '['" error message with the debug window pointing to this code:
Route::get('login', [
'as' => 'login',
'uses' => 'SessionsController#create'
]);
I tried changing it to
Route::get('login', array(
'as' => 'login',
'uses' => 'SessionsController#create'
));
but after I changed it and uploaded the file again it still looked like the original code. To make things more confusing the code should work either way, unless I am missing something.
If anyone can point out 1.)the reason for the error message - the project runs fine on my local server and 2.)why the file does not seem to be updating when I send in a new version it would be greatly appreciated! Thanks!
Your actual server is running PHP 5.3
Your local server is running PHP >=5.4
The short array syntax [] was added in PHP 5.4. See change log here.

Facebook SDK works on PHP 5.2, not on 5.3

I'm having a terrible time of it trying to implement the Facebook PHP SDK on a new server. I'm running the following code:
require('facebook.php');
$facebook = new Facebook(array(
'appId' => "###",
'secret' => "###",
));
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["page"]["liked"];
if ($like_status) {
include('fan.php');
}
else {
include('visitor.php');
}
This all works perfectly under my server running PHP 5.2.17, but breaks under PHP 5.3.3. Both servers have cURL and JSON functioning properly. As far as I can tell, no errors are being thrown, but $facebook->getSignedRequest(); is returning as null.
I'm almost certain that there's something in my server configuration that's bollocksing the whole thing up, but for the life of me I can't figure out what. Any help would be greatly appreciated. Thanks in advance!
I looked into the FB PHP SDK, getSignedRequest method and it used the $_REQUEST superglobal, the PHP manual says that in
5.3.0 - Introduced request_order. This directive affects the contents of
$_REQUEST.
Either the values of $_REQUEST are overwritten somehow. This might be something to look into.