Laravel - 如何从 Controller 设置 HTTP 响应状态代码
Laravel - How to set HTTP response status code from Controller
我是 laravel 的新手,我成功地将用户从控制器引导到适当的视图,但在某些情况下我想设置一个 http 状态代码,但它总是 returning 200
的响应代码,无论我发送什么。
这是我的测试控制器功能的代码:
public function index()
{
$data=array();
return response()->view('layouts.default', $data, 201);
}
如果我在路由中使用相同的代码,它将 return 正确的 http 状态代码,正如我在命令行中使用 curl -I 调用页面时看到的那样。
curl -I http://localhost/
为什么它在控制器中不起作用,但在路由调用中起作用?
作为新手,我肯定有一些误解,但即使是以下代码也能在路由中工作,但不能在控制器中工作:
public function index()
{
abort(404);
}
我做错了什么?
解决方案
您可以使用提到的内容 here。您将需要 return 像这样的回复:
public function index()
{
$data = ['your', 'data'];
return response()->view('layouts.default', $data)->setStatusCode(404);
} // ^^^^^^^^^^^^^^^^^^^
注意 setStatusCode($integer)
方法。
备选
您可以在 return 视图中设置额外的 header 以指定额外的数据,如 documentation 所述:
Attaching Headers To Responses
Keep in mind that most response methods
are chainable, allowing for the fluent construction of response
instances. For example, you may use the header method to add a series
of headers to the response before sending it back to the user:
return response($content)
->header('Content-Type', $type)
->header('X-Header-One', 'Header Value')
->header('X-Header-Two', 'Header Value');
我是 laravel 的新手,我成功地将用户从控制器引导到适当的视图,但在某些情况下我想设置一个 http 状态代码,但它总是 returning 200
的响应代码,无论我发送什么。
这是我的测试控制器功能的代码:
public function index()
{
$data=array();
return response()->view('layouts.default', $data, 201);
}
如果我在路由中使用相同的代码,它将 return 正确的 http 状态代码,正如我在命令行中使用 curl -I 调用页面时看到的那样。
curl -I http://localhost/
为什么它在控制器中不起作用,但在路由调用中起作用?
作为新手,我肯定有一些误解,但即使是以下代码也能在路由中工作,但不能在控制器中工作:
public function index()
{
abort(404);
}
我做错了什么?
解决方案
您可以使用提到的内容 here。您将需要 return 像这样的回复:
public function index()
{
$data = ['your', 'data'];
return response()->view('layouts.default', $data)->setStatusCode(404);
} // ^^^^^^^^^^^^^^^^^^^
注意 setStatusCode($integer)
方法。
备选
您可以在 return 视图中设置额外的 header 以指定额外的数据,如 documentation 所述:
Attaching Headers To Responses
Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. For example, you may use the header method to add a series of headers to the response before sending it back to the user:
return response($content) ->header('Content-Type', $type) ->header('X-Header-One', 'Header Value') ->header('X-Header-Two', 'Header Value');