我尝试使用nodejs和express将视频流式传输到html5视频播放器。很多人之前已经从我能找到的东西中做到了这一点,但是很少有人使用过express(在我发现的内容中)。
大多数人说这样做:
var express = require('express');
var request = require('request');
var stylus = require('stylus');
var fs = require('fs');
var path = require('path');
var url = require('url');
var http = require('http');
var app = express();
app.use(stylus.middleware({
// Source directory
src: __dirname + '/assets/stylesheets',
// Destination directory
dest: __dirname + '/public',
// Compile function
compile: function(str, path) {
return stylus(str)
.set('filename', path)
.set('compress', true);
}
}));
app.enable('trust proxy');
// Routing to the user
app.use(express.static(__dirname + "/public"));
var server = require('http').createServer(app);
// var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
server.listen(port, function() {
console.log("Server is listening on port " + port.toString());
});
app.post('/playVideo', function(req, res) {
var video = req.query.video;
var file = path.resolve(__dirname,video);
var range = req.headers.range;
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
fs.stat(file, function(err, stats) {
var total = stats.size;
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
res.writeHead(206, {
"Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type": "video/avi"
});
var stream = fs.createReadStream(file, { start: start, end: end })
.on("open", function() {
stream.pipe(res);
}).on("error", function(err) {
res.end(err);
});
});
});
不幸的是,当我尝试这样做时,我无法获得req.headers
对象。它未定义。我认为这是因为我使用了Express,尽管我必须假设Express仍然可以使用Express。
如何使用express获取标题?
谢谢!
答案 0 :(得分:0)
我认为你应该使用中间件body-parser
以下是示例:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())