1
我正在使用Codeigniter rest api。Codeigniter rest api沒有終止set_response
我知道的是,$this->set_response
終止執行並返回結果與狀態碼。
但是,當我嘗試在構造函數中執行此操作時,它忽略它並繼續執行目標方法。
我的控制器
class Posts extends REST_Controller
{
public $user_id;
public $ret_arr = [
'status' => FALSE,
'message' => ''
];
function __construct()
{
// Construct the parent class
parent::__construct();
$this->load->model('api/User_model');
$this->load->model('api/Entity_model');
$this->load->model('api/Post_model');
$token = $this->input->get_request_header('token', TRUE);
if($token!=NULL) {
$this->get_user_id($token);
}
else
{
$this->ret_arr['status'] = FALSE;
$this->ret_arr['message'] = 'Token Not Valid';
$this->set_response($this->ret_arr, REST_Controller::HTTP_UNAUTHORIZED);
}
}
public function get_user_id($token)
{
$this->user_id = $this->User_model->check_token($token);
if ($this->user_id == FALSE||$token==''||$token===null) {
$this->ret_arr['status'] = FALSE;
$this->ret_arr['message'] = 'Token Not Valid';
$this->set_response($this->ret_arr, REST_Controller::HTTP_UNAUTHORIZED);
}
}
public function addpost_post()
{
//$post_string = $this->request->body[0];
//$post = json_decode($post_string, true);
$post=$this->input->post();
if (isset($post['post_type']) && $post['post_type'] != '') {
$text = $this->input->post('text');
$type = $post['post_type'];
if ($type == 'text') {
$this->add_post_text($text);
} elseif ($type == 'url') {
} elseif ($type == 'image') {
} elseif ($type == 'video') {
}
} else {
$this->ret_arr['status'] = FALSE;
$this->ret_arr['message'] = 'Missing Post Type';
$this->set_response($this->ret_arr, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
}
}
}
當我請求該URL與報頭沒有令牌並且沒有數據發送它返回
本地主機:8080/myProject的/ API /帖子/ addpost
{「status」:false,「message」:「Missing Post Type」}和狀態422
但它必須返回
{ 「地位」:假的, 「消息」: 「令牌無效」}和狀態401
UPDATE(解決)
我解決了它通過使用$this->response()
而不是$this->set_response()
我用$這個 - >應答()代替$這個 - 解決了它> set_response(),感謝ü:) –