This article mainly introduces information about the 400 error in POST data after enabling Csrf. if you need such an error, you can refer to the error that has occurred recently and keep searching for the cause, I accidentally saw a solution article and shared it with you.
The first solution is to disable Csrf.
public function init(){ $this->enableCsrfValidation = false;}
The second solution is to add a hidden field to the form.
The third solution is to add the _ csrf field to AJAX.
var csrfToken = $('meta[name="csrf-token"]').attr("content");$.ajax({ type: 'POST', url: url, data: {_csrf:csrfToken}, success: success, dataType: dataType});
The Yii matching process and the storage location of Yii: $ app-> request-> csrfToken:
Storage location
protected function createCsrfCookie($token) { $options = $this->csrfCookie; $options['name'] = $this->csrfParam; $options['value'] = $token; return new Cookie($options); }
Verification Method
public function validateCsrfToken($token = null) { $method = $this->getMethod(); // only validate CSRF token on non-"safe" methods http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 if (!$this->enableCsrfValidation || in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) { return true; } $trueToken = $this->loadCsrfToken(); if ($token !== null) { return $this->validateCsrfTokenInternal($token, $trueToken); } else { return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken) || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken); } }
The above is all the content of this article. I hope you will like it.