解決video.js使用以後m3u8無法訪問的跨域問題

Tomcat服務器在192.168.2.111,編寫了頁面調用:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>video.js</title>
<meta charset="utf-8">
<link href="https://unpkg.com/[email protected]/dist/video-js.min.css" rel="stylesheet">
</head>
<script src="https://unpkg.com/[email protected]/dist/video.min.js"></script>
<script src="https://unpkg.com/videojs-flash/dist/videojs-flash.js"></script>
<script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
<body>
    <video id="my-player" 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,但是用video.js訪問的時候出現提示:

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/hls.html或者http://192.168.2.111:9999/xxxx/hls.html,和m3u8所在192.168.2.112域名不一致。

解決辦法,配置112上的nginx,nginx.conf(藍色是新增):

worker_processes  1;

error_log  logs/error.log 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 stat.xsl;
        }

        location /stat.xsl {
            root html;
        }
        
        location /hls {  
            #server hls fragments  
            types{  
                application/vnd.apple.mpegurl 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; 

        }  
    }
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章