请求正文中的JSON数据无效:语法错误POST Call Rest API YII2

时间:2016-05-04 07:06:08

标签: json rest yii2 yii2-basic-app

当我尝试使用Postman发帖时,我收到此错误{"name":"Bad Request","message":"Invalid JSON data in request body: Syntax error.","code":0,"status":400,"type":"yii\\web\\BadRequestHttpException"}

我的控制器是

`class CountryController扩展了ActiveController {     public $ modelClass =' app \ models \ Country';

public function behaviors()
{
    return [
        [
           'class' => 'yii\filters\ContentNegotiator',
           'only' => ['index', 'view','create'],
           'formats' => ['application/json' => Response::FORMAT_JSON,],

        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'index'=>['get'],
                'view'=>['get'],
                'create'=>['post'],
                'update'=>['put'],
                'delete' => ['delete'],
                'deleteall'=>['post'],
            ],

        ],
    ];
}

}`

添加了

'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]

api / config.php 文件中。

我错了?

2 个答案:

答案 0 :(得分:0)

试试这个

lang: 'en'

答案 1 :(得分:-1)

我在php 7上使用wordpress 4.7,也遇到了空请求体的问题。

我的控制器:

add_action('rest_api_init', function()
{
     register_rest_route('v0', '/accounts/(?P<slug>[a-z0-9_\-]+)/accounts', array(
        'methods' => 'GET',
        'callback' => function($request)
        {
            try {
               return 'hello';
            }
            catch (Exception $e) {
                $error = json_decode($e->getMessage(), true);
                return new WP_Error($error['status_code'], $error['message'], "");
            }
        }
    ));
});

响应错误:

{"code":"rest_invalid_json","message":"Invalid JSON body passed.","data":{"status":400,"json_error_code":4,"json_error_message":"Syntax error"}}

我没有找到任何解决方案,而不是在WP核心中更改:wp-includes / rest-api / class-wp-rest-request.php和chaning line 672用于空状态的条件检查。

$params = json_decode( $this->get_body(), true );