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

问题描述 投票:0回答:2

当我尝试使用 Postman 发帖时,出现此错误

{"name":"Bad Request","message":"Invalid JSON data in request body: Syntax error.","code":0,"status":400,"type":"yii\\web\\BadRequestHttpException"}

我的控制器是

`类 CountryController 扩展了 ActiveController { 公共 $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 文件中。

我哪里错了??

json rest yii2 yii2-basic-app
2个回答
0
投票

试试这个

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'=>['post'],
                'delete' => ['delete'],
                'deleteall'=>['post'],
            ]
        ]
    ];
}

-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 并更改第 672 行以进行条件检查是否为空主体。

$params = json_decode( $this->get_body(), true );
© www.soinside.com 2019 - 2024. All rights reserved.