Sunday, 9 April 2017

run node.js code on a virtual machine with centos7.2, request for mp4 file, but response 302

run node.js/react code on a virtual machine with centos7.2, request for mp4 file, but response 302, and what is this "Request URL?":

http://172.16.6.19/disable/disable.htm?url_type=%E4%B8%8B%E8%BD%BD%E5%B7%A5%E5%85%B7/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E4%B8%8B%E8%BD%BD&plc_name=%E5%BA%94%E7%94%A8%E7%AE%A1%E7%90%86

but if i run the same code on a physical machine, everything is ok

client side code using react:

 render() {
                return (
                    <div id="S05ContainerId">
                        <div id="videoContainerId">
                            <video controls autoPlay={true} width={1920}>
                                <source src={`${globalClientServerUrl}/video/dtdream.mp4`} type="video/mp4"/>
                                your browser doesn't support video
                            </video>
                        </div>
                        <ScreenSwitch/>
                        <BackToHomePage/>
                    </div>
                )
            }

server side code with node.js express.router

const express = require('express');
const router  = express.Router();
const fs      = require('fs');
const path    = require('path');

router.get('/video/:filename', function (req, res, next) {
    const fileName = req.params.filename;
    console.log(`request video/${fileName}`);
    const filePath = path.resolve(__dirname, `../serverRouter/${fileName}`);
    const stat     = fs.statSync(filePath);
    const total    = stat.size;
    if (req.headers['range']) {
        const range        = req.headers.range;
        const parts        = range.replace(/bytes=/, "").split("-");
        const partialStart = parts[0];
        const partialEnd   = parts[1];

        const start     = parseInt(partialStart, 10);
        const end       = partialEnd ? parseInt(partialEnd, 10) : total - 1;
        const chunkSize = (end - start) + 1;
        // console.log('RANGE: ' + start + ' - ' + end + ' = ' + chunkSize);

        const stream = fs.createReadStream(filePath, {start: start, end: end});

        res.writeHead(206, {
            'Content-Range':  'bytes ' + start + '-' + end + '/' + total,
            'Accept-Ranges':  'bytes',
            'Content-Length': chunkSize,
            'Content-Type':   'video/mp4'
        });
        stream.pipe(res);
    } else {
        console.log('ALL: ' + total);
        res.writeHead(200, {'Content-Length': total, 'Content-Type': 'video/mp4'});
        fs.createReadStream(filePath).pipe(res);
    }

});

enter image description here



via 项少龙

No comments:

Post a Comment