Php Yii2 rest api未返回响应代码和状态
我试图获取(StatusCode)作为RESTAPI的响应,而它只返回字段名和错误消息,如下所示Php Yii2 rest api未返回响应代码和状态,php,rest,yii,yii2,yii2-advanced-app,Php,Rest,Yii,Yii2,Yii2 Advanced App,我试图获取(StatusCode)作为RESTAPI的响应,而它只返回字段名和错误消息,如下所示 [{"field":"Email","message":"Email \"ali@ali.ali\" has already been taken."}] 我补充了一些回应 'response' => [ 'class' => 'yii\web\Response', 'on beforeSend' => function ($event) {
[{"field":"Email","message":"Email \"ali@ali.ali\" has already been taken."}]
我补充了一些回应
'response' => [
'class' => 'yii\web\Response',
'on beforeSend' => function ($event) {
$response = $event->sender;
if ($response->data !== null && Yii::$app->request->get('suppress_response_code')) {
$response->data = [
'success' => $response->isSuccessful,
'data' => $response->data,
];
$response->statusCode = 200;
}
},
],
您可以在您的操作中添加此代码,然后再返回您的响应
if ("some error checking goes there") {
Yii::$app->response->statusCode = 422;//I preferred that error code
return [
"data" => [
'errors' => [
'fieldname' => "Field Name is invalid",
]
],
];
}
因此,只有通过
$\u GET
发送suppress\u response\u code
时,您才可以设置状态码,但在任何情况下,我都不会收到状态响应….@AliRaza尝试删除第二部分Yii::$app->request->GET('suppress\u response\u code')
,并对其进行测试。如果失败,则$response->data
为空。将控制器响应设置为“return$model;”而不是“return$model->errors;”将自动设置相应的状态代码。
if ("some error checking goes there") {
Yii::$app->response->statusCode = 422;//I preferred that error code
return [
"data" => [
'errors' => [
'fieldname' => "Field Name is invalid",
]
],
];
}