当我尝试使用 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 文件中。
我哪里错了??
试试这个
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'],
]
]
];
}
我在 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 );