how to Json encode in yii2?

后端 未结 3 1256
时光说笑
时光说笑 2021-01-18 03:36

Attempting to encode json and receive 400: Bad Request in yii2. I am trying to encode in Rest client but it is not working properly.



        
相关标签:
3条回答
  • 2021-01-18 04:17

    Solution 1: In case if all your controller's actions will deliver json you may also consider extanding yii\rest\Controller instead of yii\web\Controller :

    namespace app\controllers;
    
    use Yii;
    
    class UserController extends \yii\rest\Controller
    {
        public function actionRegister()
        {
            $username = Yii::$app->request->post('username');
            return $username;
        }
    }
    

    NOTE: you may also use ActiveController which extends yii\rest\Controller (see rest docs) if you need to handle CRUD operations.


    Solution 2: A different approach when extending yii\web\Controller is by using yii\filters\ContentNegotiator. Note that setting $enableCsrfValidation to false may be mandatory here as it is explained in its related docs :

    Whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to true. When CSRF validation is enabled, forms submitted to an Yii Web application must be originated from the same application. If not, a 400 HTTP exception will be raised.

    Note, this feature requires that the user client accepts cookie. Also, to use this feature, forms submitted via POST method must contain a hidden input whose name is specified by $csrfParam. You may use yii\helpers\Html::beginForm() to generate his hidden input.

    The above code may be rewritten this way :

    namespace app\controllers;
    
    use Yii;
    use yii\web\Controller;
    use yii\filters\ContentNegotiator;
    use yii\web\Response;
    
    class UserController extends Controller
    {
        public $enableCsrfValidation = false;
    
        public function behaviors()
        {
            return [
                'contentNegotiator' => [
                    'class' => ContentNegotiator::className(),
                    'formats' => [
                        'application/json' => Response::FORMAT_JSON,
                    ],
                    'only' => ['register'],
                ],
            ];
        }
    
        public function actionRegister()
        {
            $username = Yii::$app->request->post('username');
            return $username;
        }
    }
    
    0 讨论(0)
  • 2021-01-18 04:17
    public function actionRegister()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $model = new TblUserRegistration();
        return $_POST['username'];
    }    
    
    0 讨论(0)
  • 2021-01-18 04:40

    i think 400 have nothing to do with json_encode

    google "yii2 csrf" for more information.

    public function actionRegister()
    {
        // is not safe
        Yii::$app->controller->enableCsrfValidation = false;
    
        // set response header
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
      
        $model = new TblUserRegistration();
        $username = $_POST['username'];
        return $username;
    }

    or add scrf in view: form:

    <input name="_csrf" type="hidden" id="_csrf" value="<?= Yii::$app->request->csrfToken ?>">

    meta:

    <?= Html::csrfMetaTags() ?>

    0 讨论(0)
提交回复
热议问题