7

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.

<?php 
    namespace app\controllers;
    use Yii;
    use yii\filters\AccessControl;
    use yii\web\Controller;
    use yii\filters\VerbFilter;
    use app\models\TblUserRegistration;
    class UserController extends Controller
    {
        public function actionRegister()
        {
            $model = new TblUserRegistration();
            $username = $_POST['username'];
            echo json_encode($username);
        }
    }
?>

Error image.enter image description here

Error imageenter image description here

7
  • 1
    set response format to \yii\web\Response::FORMAT_JSON; Commented Jan 28, 2016 at 9:05
  • Insane is right. Use \yii\web\Response::FORMAT_JSON; Commented Jan 28, 2016 at 9:12
  • 1
    add hidden field in form for csrf: ` <input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />` Commented Jan 28, 2016 at 9:20
  • @InsaneSkull Actually I want to use that in Advance Rest client in google chrome Because i want to use that in web service.So i don't have any form. I just need pure json encoded data. Commented Jan 28, 2016 at 9:27
  • 1
    Then set \Yii::$app->response->format = Response::FORMAT_JSON; should work for you. Commented Jan 28, 2016 at 9:29

3 Answers 3

2
public function actionRegister()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $model = new TblUserRegistration();
    return $_POST['username'];
}    
Sign up to request clarification or add additional context in comments.

Comments

1

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;
    }
}

Comments

1

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() ?>

7 Comments

Nice googling about csrf on bad request.
@suibber Thanks for answer but still it doesn't work.is there need any more config in yii?
@suibber i have attached image in my question.
try to use get instead of post ? and i can't see the response body on your image
@suibber When i use get it throws 500 internal server error.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.