You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

在CodeIgniter中实现SSE遇错误:EventSource响应MIME类型不符

Fixing the SSE MIME Type Error in CodeIgniter

Hey there! That error you're hitting is super common when setting up Server-Sent Events (SSE) in CodeIgniter—your server is sending back a text/html content type instead of the required text/event-stream that EventSource expects. Let's walk through how to fix this step by step.

1. Set Correct Response Headers in Your Controller

The core fix lies in ensuring your CodeIgniter controller method for the SSE endpoint sends the right HTTP headers. Here's how to update your video_calling method:

public function video_calling($client_user_id) {
    // Clear any existing output buffer to prevent extra content from being sent
    ob_end_clean();

    // Set SSE-specific response headers using CodeIgniter's output class
    $this->output
        ->set_content_type('text/event-stream')
        ->set_header('Cache-Control: no-cache')
        ->set_header('Connection: keep-alive');

    // Example SSE message structure (follow this format for all events)
    echo "data: {\"message\": \"Connection established\", \"client_id\": \"{$client_user_id}\"}\n\n";
    flush(); // Push the data to the client immediately

    // If you need ongoing updates, add a loop here with sleep()
    // Make sure to handle shutdowns properly to avoid hanging connections
}

Critical Notes for the Controller:

  • No extra output: Don't load any views, echo HTML, or leave trailing spaces/newlines in your controller file—even a single stray space will force the response to be text/html instead of text/event-stream.
  • Buffer cleanup: ob_end_clean() clears any buffered content from earlier in the request (like from controller constructors or hooks) that might interfere with header settings.

2. Tweak Your Frontend Code (Optional but Helpful)

Your frontend code is mostly solid, but here's a cleaned-up version with error handling to make debugging easier:

if(typeof(EventSource) !== "undefined") {
    // Combine URL construction for cleaner code
    var sseUrl = "<?php echo base_url('lawyer/consultation/video_calling/' . $client_user_id); ?>";
    var source = new EventSource(sseUrl);

    source.onmessage = function(event) {
        var imgUrl = "<?php echo base_url('assets/images/main...'); ?>";
        // Parse incoming data if you sent JSON
        var data = JSON.parse(event.data);
        console.log('Received SSE data:', data);
        // Update your UI here
    };

    // Add error handling to catch connection issues
    source.onerror = function(error) {
        console.error('SSE Connection Error:', error);
        source.close(); // Clean up the connection
    };
} else {
    // Fallback for browsers that don't support SSE
    alert('Your browser does not support Server-Sent Events.');
}

3. Troubleshooting Additional Issues

If you're still seeing the error after setting the headers:

  • Check for redirects: Ensure your SSE URL isn't redirecting (e.g., HTTP to HTTPS or trailing slash mismatch)—redirect responses often default to text/html.
  • Verify server configuration: Confirm your web server (Apache/Nginx) isn't overriding the Content-Type header. CodeIgniter's headers usually take precedence, but check .htaccess rules or server configs just in case.
  • Test the endpoint directly: Visit the SSE URL in your browser—you should see raw data: lines instead of an HTML page. If you see HTML, your controller is still outputting extra content.

内容的提问来源于stack exchange,提问作者Jenna Rose

火山引擎 最新活动