设置响应状态代码 [英] Set Response Status Code
问题描述
我有一个API调用,我需要能够运行一些检查,并可能返回各种状态代码。我不需要自定义视图或任何东西,我只需要返回正确的代码。如果用户没有通过正确的凭据,我需要返回401状态。如果他们没有发送支持的请求格式,我需要返回400状态。
I have an API call for which I need to be able to run some checks and potentially return various status codes. I don't need custom views or anything, I just need to return the proper code. If the user hasn't passed proper credentials, I need to return a 401 status. If they haven't sent a supported request format, I need to return a 400 status.
因为它是一个API,我真正想做的是设置响应状态并退出一个简单的,愚蠢的消息为什么请求失败(可能使用退出
)。刚好足以让工作完成,但我没能得到这个工作正常。我尝试使用PHP的 header()
和Cake的 $ this-> header()
控制器),但是虽然我得到退出消息,标题显示 200 OK
状态。
Because it's an API, all I really want to do is set the response status and exit with a simple, stupid message about why the request failed (probably using a exit
). Just enough to get the job done, but I haven't been able to get this to work right. I've tried using PHP's header()
and Cake's $this->header()
(this is all in the controller), but although I get the exit message, the header shows a 200 OK
status.
使用代码下面,我得到消息,但头没有设置。
Using the code below, I get the message, but the header isn't set. What am I missing?
if( !$this->auth_api() ) {
header( '401 Not Authorized' );
exit( 'Not authorized' );
}
推荐答案
PHP <= 5.3
header()
函数具有状态代码的参数。
PHP <=5.3
The header()
function has a parameter for status code. If you specify it, the server will take care of it from there.
header('HTTP/1.1 401 Unauthorized', true, 401);
PHP> = 5.4
查看Gajus answer: http://stackoverflow.com/a/14223222/362536
这篇关于设置响应状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!