Set the HTTP content type response to “application/json” in php

偶尔善良 提交于 2020-02-08 02:25:08

问题


I have a question. I have the folowing condition :

You should return an HTTP 500 status code and more details about the error in the message body. Set the HTTP content type response to “application/json”.The error detail must be in JSON format as described below:

 {
    "ErrorCode" : 402,
    "ErrorMessage" : "Item"
  }

I tried like this :

if(!Gain::verifyIfUserExistByIdm($aOutput['UserId'])){
    header("HTTP/1.0 500 Internal Server Error");
    return json_encode(array('ErrorCode'=>407,'ErrorMessage'=>'Error'));
    die();
}

But not work, can you help me please? Thx in advance


回答1:


You need to output the JSON (not just return it), and let the client know that the content is JSON by setting the Content-Type:

// The user does not exist
if ( ! Gain::verifyIfUserExistByIdm($aOutput['UserId'])) {

    // If the user does not exist then "Forbidden" would make sense
    header("HTTP/1.0 403 Forbidden");

    // Let the client know that the output is JSON
    header('Content-Type: application/json');

    // Output the JSON
    echo json_encode(array(
        'ErrorCode'    => 407,
        'ErrorMessage' => 'Error',
    ));
    // Always terminate the script as soon as possible
    // when setting error headers
    die;
}


来源:https://stackoverflow.com/questions/31522593/set-the-http-content-type-response-to-application-json-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!