解决使用以后m3u8无法访问的跨域问题

时间:2025-04-24 21:59:24

Tomcat服务器在192.168.2.111,编写了页面调用:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title></title>
<meta charset="utf-8">
<link href="/@6.11.0/dist/" rel="stylesheet">
</head>
<script src="/@6.11.0/dist/"></script>
<script src="/videojs-flash/dist/"></script>
<script src="/videojs-contrib-hls/dist/"></script>
<body>
    <video class="video-js" controls>
        <source src="http://192.168.2.112:8080/hls/1000246_2_2.m3u8" type="application/x-mpegURL">
        <p class="vjs-no-js">not support</p>
    </video>
    <script type="text/javascript">
        var player = videojs('my-player', {
            width : 400,
            heigh : 200
        });
    </script>
</body>
</html>

在主机192.168.2.112用了nginx搭建hls流媒体服务器,生成了m3u8,但是用访问的时候出现提示:

Access to XMLHttpRequest at 'http://192.168.2.112:8080/hls/1000246_2_2.m3u8' from origin 'http://localhost:9999' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

因为Tomcat的访问URL里是:

http://localhost:9999/xxxx/或者http://192.168.2.111:9999/xxxx/,和m3u8所在192.168.2.112域名不一致。

解决办法,配置112上的nginx,(蓝色是新增):

worker_processes  1;

error_log  logs/ info;

events {
    worker_connections  1024;
}

rtmp {
    server {
        listen 1935;

        application live {
            live on;
        }
        
        application hls {
            live on;
            hls on;  
            hls_path temp/hls;  
            hls_fragment 8s;  
        }
    }
}

http {
    server {
        listen      8080;

        location / {
            root html;
        }
        
        location /stat {
            rtmp_stat all;
            rtmp_stat_stylesheet ;
        }

        location / {
            root html;
        }
        
        location /hls {  
            #server hls fragments  
            types{  
                application/ m3u8;  
                video/mp2t ts;  
            }  
            alias temp/hls;  
            expires -1;  
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Headers X-Requested-With;
            add_header Access-Control-Allow-Methods GET,POST,OPTIONS; 

        }  
    }
}