【问题标题】:How to set custom response status code in Slim Framework如何在 Slim Framework 中设置自定义响应状态码
【发布时间】:2016-11-21 11:32:06
【问题描述】:

我在我的新项目中使用 Angular JS、PHP 和 Slimframework。

我在 Angular JS 中使用 Promise,但如您所知,如果响应状态代码从 API 返回为 200,则只有“成功”部分有效。

在 Slimframework 中,默认响应状态码是 200,我所有的请求都返回状态码 200。(如果没有错误是正常的)

但我想做一些验证,如果验证失败,我只想在 Slim 框架中更改或设置自定义状态代码。在这种情况下,我将能够使用“错误”代码块在 Angular JS 中发现问题

例如:

SlimFramework 部分

$app->get('/getUserInformations/{user_id}', function(Request $request, Response $response){

    if(isLoggedIn()){

        //Do something and send an answer with status code 200

    }else{

        //Send some errors with status code 500 or something else

    }

});

Angular JS 部分:

user.getUserInformations = function(){
    var defer = $q.defer();

    $http.get($rootScope.defaultApiPath + '/getUserInformations/1')
        .success(function(response){

            //if status code is 200 this means user logged in. Do something

            defer.resolve(response);
        })
        .error(function(error, status){

            // if status code is 500 this means not logged in. Show error message

            defer.reject(error);
        });

    return defer.promise;
};

在 SlimFramework 的文档中,我发现了类似

$newResponse = $response->withStatus(302);

$data = array('name' => 'Rob', 'age' => 40);
$newResponse = $oldResponse->withJson($data, 201);

但我无法使用它们。给我一些错误,找不到方法..

简而言之,我的问题是,如何在 slim 框架中设置自定义状态码..

提前谢谢你

【问题讨论】:

  • return $response->withStatus(xxx);
  • 你能把它写成答案吗?我想将其设置为正确答案:) 非常感谢。 50 行问题,1 行答案。太好了..

标签: angularjs frameworks slim


【解决方案1】:

您正在寻找的答案是......

return $response->withStatus(xxx);

http://www.slimframework.com/docs/objects/response.html#the-response-status

【讨论】:

    猜你喜欢
    • 2021-12-26
    • 2020-04-20
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多