我有一个有效的获取请求。我从堆栈溢出中拿走了它。当浏览器向快速节点发出获取请求时,js服务器视频开始播放。但是我想将其更改为发布请求,因为我想选择所需的视频。所以我想在不刷新页面的情况下更改播放器视频。我将此方法更改为发布,并为其添加了正文解析器。这是我的方法:
app.post('/api/video', urlencodedParser , function(req, res) {
var folder = req.body.folder
var path = 'D:/VideoDirectory/'+ folder + '/clip.mp4'
const stat = fs.statSync(path)
const fileSize = stat.size
const range = req.headers.range
if (range) {
const parts = range.replace(/bytes=/, "").split("-")
const start = parseInt(parts[0], 10)
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize-1
const chunksize = (end-start)+1
const file = fs.createReadStream(path, {start, end})
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
}
res.writeHead(206, head)
file.pipe(res)
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
}
res.writeHead(200, head)
fs.createReadStream(path).pipe(res)
}
})
这是我的 ajax 帖子请求:
var folder = {folder: "testFolder"}
$.ajax({
type: 'POST',
url: '/api/video',
data: folder,
success: function(data){
alert('post request sent');
}
});
}
在我提出这个帖子请求后,视频将进入浏览器。我知道这一点,因为互联网下载管理器试图抓住它。它具有正确的文件大小。但是这个视频不会进入html5播放器。我怎样才能用这个帖子回复来喂养玩家?我想在不引用页面的情况下更改视频。这是我的html5视频播放器代码:
<video id="videoPlayer" controls>
<source src="http://xxx.xxx.xx.xx:4000/api/video" type="video/mp4">
</video>
感谢@btzr我使用了带有参数的获取请求。这是最后一种形式:
app.get('/api/video/:folder' , function(req, res) {
var streamer = req.params.folder
const path = 'D:/VideoDirectory/' + folder+ '/clip.mp4'
const stat = fs.statSync(path)
const fileSize = stat.size
const range = req.headers.range
if (range) {
const parts = range.replace(/bytes=/, "").split("-")
const start = parseInt(parts[0], 10)
const end = parts[1]
? parseInt(parts[1], 10)
: fileSize-1
const chunksize = (end-start)+1
const file = fs.createReadStream(path, {start, end})
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
}
res.writeHead(206, head)
file.pipe(res)
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
}
res.writeHead(200, head)
fs.createReadStream(path).pipe(res)
}
})
我只是用javascript更改视频播放器的src:
var player = document.getElementById('videoPlayer');
player.src = 'http://xxx.xxx.xx.xx:4000/api/video/' + folder;
视频播放器在 src 更新时向服务器发出获取请求。