項目流程大概是這樣的,瀏覽器從a服務器獲取到流服務器地址和用戶名密碼,然後從流服務器上通過basic authentication取流
這裏有兩點:1、跨域問題 2 、要做訪問驗證
是開啓nginx這邊的basic authentication驗證,這個網上的方法很多,不在累述了,網上找了一篇,看看就會了,改好後使用vlc取流,按要求輸入用戶名,密碼就能取到流了
然後是flv.js的使用:在createPlayer的第二個參數config里加入basic authentication的http頭
例如:
this._videoPlayerObj = FlvJs.createPlayer({
type: 'flv',
url: url,
isLive: true,
}, {
enableStashBuffer: false,
stashInitialSize: 128,
autoCleanupSourceBuffer: true,
headers:{
'Authorization':'Basic '+btoa(unescape(encodeURIComponent("username:password")))
}
}
);
如上,其中的headers部分就是要添加上的http頭部,這個屬性在最新的flv.js裏是支持的,作者根據使用者的反饋更新過
這時,來通過flv.j獲取視頻,實際還是不行的,通過抓包發現發送的請求是OPTION!!
OPTIONS /live?port=1935&app=hls&stream=jt_n127000000001_c3_s0 HTTP/1.1
Host: 192.168.110.166
Connection: keep-alive
Accept: */*
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Origin: http://localhost:8090
Sec-Fetch-Mode: cors
Referer: http://localhost:8090/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
這個是誇域訪問時的預檢請求,網上文章很多,找幾篇來看看就明白了,處理這個問題在服務端,也就是nginx端來解決,博主最後找的了這篇文章來處理的,就是在配置里加上對OPTIONS的處理,如下
if ( $request_method = 'OPTIONS' ) {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Max-Age' '604800';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Access-Token,Blog-ID';
return 200;
}
這樣當方法是OPTION時,按這個腳本來返回。
到此,通過flv.js就可以訪問到流了嗎,不行,上面的腳本還差點
因爲我們需要做basic authentication認證,會在http頭裏加上Authorization字段,但是上面的腳本Access-Control-Allow-Headers裏並沒有指明Authorization是允許的。瀏覽器會包如下錯:
Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response
既然說authorization是not allowed,哪就把它加上
add_header 'Access-Control-Allow-Headers' 'DNT,Authorization,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Access-Token,Blog-ID';
這時,再來訪問就可以了。
以上就是配置時遇到的問題並解決的全過程