Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

javascript - How to play a protected video streaming node api in frontend

I've created a video streaming server with NodeJs which is protected with jwt token.

router.get("/video-streams/:id", authenticateUser, async (req, res) => {
  try {
    let id = req.params.id;
    userdata = await User.aggregate([
      { $match: { email: req.user.data } },
      { $unwind: "$videos" },
      { $match: { "videos._id": ObjectId(id) } },
    ]);
    if (userdata.length <= 0) {
      res.status(404).send({
        message: "No Video Found",
      });
    } else {
      const path = userdata[0].videos.path;
      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]) : 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);
      }
    }
  } catch (err) {
    res.status(500).send({ message: "Error happened ", err });
  }
});

Now I'm calling this endpoint in html like

  <ReactPlayer
      controls
      width="100%"
      height="100%"
      url={"http://localhost:8080/api/v1/video-streams/" + path}
    ></ReactPlayer>

It is giving me Unauthorised error as i'm not passing Authorization header in api call. How can I pass auth header in html video tag?

question from:https://stackoverflow.com/questions/65841460/how-to-play-a-protected-video-streaming-node-api-in-frontend

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...