Home  >  Article  >  PHP Framework  >  Solve the problem of yii2.0 api post error

Solve the problem of yii2.0 api post error

藏色散人
藏色散人Original
2020-07-20 10:26:182630browse

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".

Solve the problem of yii2.0 api post error

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: &#39;demo.php&#39;,//发送验证码的url
             type: &#39;post&#39;,
             data: {
                 _csrf:"<?=Yii::$app->request->csrfToken?>",
                 mobile:123
             },
             success: function(){
                     alert(&#39;发送成功&#39;);
             },
             error: function(){
                 alert(&#39;发送失败&#39;);
                 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn