S
S
Sergey Zolotarev2021-09-06 10:42:50
Yii
Sergey Zolotarev, 2021-09-06 10:42:50

How to fix 400 error when sending POST request?

Good day!
For the past few days, I've been facing a problem when testing the backend API on Yii2 and the very basis from Postman algorithms:
6135c48a39b1e832763762.png
When entering a POST request, Yii2 itself accesses the controller and its action, to whom I directly access and it should only display text and nothing else:

<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\View;
...
use yii\web\NotFoundHttpException;
class SiteController extends Controller{
  ...
  public function actionServiceCodeCenter($service){
    Yii::$app->controller->enableCsrfValidation = false;
    $q = json_decode($_POST['serviceQuery']);
    
    switch($service){
                   ...
  if($_POST['serviceQuery']){
          $source = $q['fsq'];

          $generateCode = [
            ceil(getRandomFromRange(1000,9999)),
            ceil(getRandomFromRange(2000,4600))
          ];

          $isSignUp = $source['svc'] === 'SignUp' ? TRUE : FALSE;
          $isForgot = $source['svc'] === 'Forgot' ? TRUE : FALSE;

          if($isSignUp){ $newCode = $generateCode[0]; }
          else if($isForgot){ $newCode = $generateCode[1]; }

          throw new HttpException(201 ,$newCode);
          
        }
        else{ throw new HttpException(405 ,'Query conflict'); }
      break;
      default: throw new HttpException(404 ,'Service not found'); break;
    }
                }
}
?>

And during the test, Yii2 brought out the 400th error and still has not found out the cause of the occurrence. What is wrong with the algorithm and how to get rid of the error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Bay, 2021-09-06
@kawabanga

use yii\web\Controller;
->
yii\rest\Controller
and read about REST controllers.
Or about disabling csrf in web controllers (bad).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question