Home > Article > PHP Framework > Solve the problem of yii2.0 api post error
Yii2.0 api post error solution: 1. Turn off "_csrf" verification; 2. Add hidden fields to the form; 3. Add "_csrf" data field in Ajax; 4. Change "post "Submit is changed to "get".
400 request error occurs when submitting data via POST in Yii2.0
1. How to find the problem
Use Chrome browser, check the error, go to the network to check the response:
Bad Request (#400): Unable to verify your date submission. (无法验证提交的数据)
Recommendation: "yii tutorial"
2. Solution
(1) Turn off _csrf verification
public function init(){ $this->enableCsrfValidation = false; }
(2) Add a hidden field in the form
<input name="_csrf" type="hidden" id="_csrf" value="<?= Yii::$app->request->csrfToken ?>">
If we are using the helper class of the Yii framework to generate the form, it It will come with the _csrf field, and we do not need to add additional hidden fields.
(3) Add _csrf data field in Ajax
$.ajax({ url: 'demo.php',//发送验证码的url type: 'post', data: { _csrf:"<?=Yii::$app->request->csrfToken?>", mobile:123 }, success: function(){ alert('发送成功'); }, error: function(){ alert('发送失败'); return false; } })
(4) The simplest method is to change post submission to get
Note: Yii framework has its own Data verification function, if the data submitted by our post does not have the same verification data field as the _csrf corresponding to the framework, the submitted data will be regarded as an untrusted field, and a 400 error will occur.
The above is the detailed content of Solve the problem of yii2.0 api post error. For more information, please follow other related articles on the PHP Chinese website!