Access-Control-Allow-Origin is not showing up in response headers from codeigniter

后端 未结 4 963
太阳男子
太阳男子 2021-01-03 08:24

My Codeigniter file says

$CI->output->set_header(\"Access-Control-Allow-Origin: *\");
$CI->output->set_header(\"Access-Control-Expose-Headers: Ac         


        
4条回答
  •  一向
    一向 (楼主)
    2021-01-03 09:09

    after some digging around, i found that $CI->output->set_header() does work - when there isn't an error or exception.

    When there is an error or exception that CI can catch, the output & view classes are bypassed completely and the appropriate error pages are rendered with include(VIEWPATH.'errors/'.$template.'.php') and headers sent with set_status_header($status_code) (located at /core/Common.php)

    see /core/Exceptions.php

    here's a sample:

        /**
         * General Error Page
         *
         * Takes an error message as input (either as a string or an array)
         * and displays it using the specified template.
         *
         * @param   string      $heading    Page heading
         * @param   string|string[] $message    Error message
         * @param   string      $template   Template name
         * @param   int     $status_code    (default: 500)
         *
         * @return  string  Error page output
         */
        public function show_error($heading, $message, $template = 'error_general', $status_code = 500)
        {
            set_status_header($status_code);
    
            $message = '

    '.implode('

    ', is_array($message) ? $message : array($message)).'

    '; if (ob_get_level() > $this->ob_level + 1) { ob_end_flush(); } ob_start(); include(VIEWPATH.'errors/'.$template.'.php'); $buffer = ob_get_contents(); ob_end_clean(); return $buffer; }

    it's annoying in that it makes DRY less straight forward. to work around it, i suggest you create a helper function, for example (untested):

    function my_generate_headers($headers=array(),$useOutputClass=true)
    {
        if(is_array($headers) && count($headers)<1) return false;
    
        foreach($headers AS $eHeader)
        {
            ($useOutputClass) ? 
                        get_instance()->output->set_header('X-Powered-By: C-C-C-Cocaine') : 
                        @header('X-Powered-By: Errors',true);
        }
    
        return true;
    }
    

    use that function in your different error pages at /errors/error_*.php as well as in your controllers.

提交回复
热议问题