Home > PHP Framework > YII > body text

Solve the problem of yii2.0 api post error

藏色散人
Release: 2020-07-20 10:26:18
Original
2489 people have browsed it

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.   (无法验证提交的数据)
Copy after login

Recommendation: "yii tutorial"

2. Solution

(1) Turn off _csrf verification

public function init(){
    $this->enableCsrfValidation = false;
}
Copy after login

(2) Add a hidden field in the form

Copy after login

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:"request->csrfToken?>",
                 mobile:123
             },
             success: function(){
                     alert('发送成功');
             },
             error: function(){
                 alert('发送失败');
                 return false;
             }
         })
Copy after login

(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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!