【发布时间】:2014-04-02 20:11:03
【问题描述】:
我正在尝试从 Laravel 返回 400 状态码。我在控制器中设置了一个简单的测试:
return Response::json(["Test", "Array"], 400);
看看网络检查器,我得到了 200 OK。
如果我转储响应:
object(Illuminate\Http\JsonResponse)#306 (8) {
["data":protected]=>
string(16) "["Test","Array"]"
["callback":protected]=>
NULL
["headers"]=>
object(Symfony\Component\HttpFoundation\ResponseHeaderBag)#315 (5) {
["computedCacheControl":protected]=>
array(1) {
["no-cache"]=>
bool(true)
}
["cookies":protected]=>
array(0) {
}
["headerNames":protected]=>
array(3) {
["cache-control"]=>
string(13) "Cache-Control"
["date"]=>
string(4) "Date"
["content-type"]=>
string(12) "Content-Type"
}
["headers":protected]=>
array(3) {
["cache-control"]=>
array(1) {
[0]=>
string(8) "no-cache"
}
["date"]=>
array(1) {
[0]=>
string(29) "Wed, 02 Apr 2014 20:03:14 GMT"
}
["content-type"]=>
array(1) {
[0]=>
string(16) "application/json"
}
}
["cacheControl":protected]=>
array(0) {
}
}
["content":protected]=>
string(16) "["Test","Array"]"
["version":protected]=>
string(3) "1.0"
["statusCode":protected]=>
int(400)
["statusText":protected]=>
string(11) "Bad Request"
["charset":protected]=>
NULL
}
可以看到状态码设置为400,statusText为Bad Request。
基本上我将 Backbone.js 与 Laravel 结合使用,并且需要返回 200 以外的状态码来捕获保存时的错误。
这似乎是一件很简单的事情,有人知道我遇到了什么问题吗?
更新
经过一番抨击后,我找到了一个(不是很理想的)解决方法来实现我所需要的,并在 Laravel GitHub 上记录了一个问题:https://github.com/laravel/laravel/issues/2796
基本上,我将控制器排除在外,并尝试将其作为路线:
Route::get('/bad-request', function() {
$response['state'] = "error";
$response['errors'] = ["name" => ["A product name is required"]];
return Response::json($response, 400);
});
同样的问题,返回 200。暂时找到了这个解决方法:
Route::get('/bad-request', function() {
$response['state'] = "error";
$response['errors'] = ["name" => ["A product name is required"]];
http_response_code(400);
return Response::json($response, 400);
});
我宁愿用 Laravel 来做这件事,也不愿用 PHP 来强制它。我也试过Response::make,效果完全一样。
【问题讨论】:
-
我不相信 Web 层处理 Json 响应的方式与处理 API 调用的方式相同。如果要将 404 返回到 Web 层,则必须使用
return Response::error(404)之类的内容。但是,我很困惑为什么这很重要 - 只要您从用于发出请求的工具中获得正确的响应,为什么 Web 层需要看到 404? -
@RyanHavoc 我不明白为什么你会在你的网络检查器中得到 200 响应。我自己测试了一下,也得到了 400。即使你的转储返回 400。在我们没有看到的灌木丛中肯定有更多。
-
这应该可以。你能分享你的完整控制器吗?
标签: backbone.js laravel laravel-4 http-headers http-status-codes