'How to serve MP4 using an express Rest API server so it's compatible with mobile?

I have an express rest API server, and I am trying to use it to get an MP4 file from an S3 bucket and serve it. The video is displayed OK on my desktop, but doesn't work on my iPhone 10. See image below.

It's not a problem with my phone's ability to play this specific file because when I access it on my phone directly from the bucket, it works. So it must be something with how my server is getting or serving the file. Any suggestions?

app.get("/video/:userId", async (request, response) => {
  s3.getObject({ Bucket: 'user-videos', Key: request.params.userId }, function(err, data) {
    if (err) {
      console.log(err);
    } else {
      response.set("Content-Type", "video/mp4");
      response.send(data.Body);
    }
  });
});

enter image description here



Solution 1:[1]

One must check in requested source accepts range, if yes, serve the content accordingly:

app.get("/video/:userId", async (request, response) => {
  s3.getObject({ Bucket: 'user-videos', Key: request.params.userId }, function(err, imgData) {
    if (err) {
      console.log(err);
    } else {
      const range = request.get("Range");
      let start = 0;
      let end = "";
      let code = 200;
      if (range) {
        const result = range.match(/bytes=(\d+)-(\d*)/);
        if (result !== null) {
          start = result[1];
          end = result[2];
        }
        code = 206;
      }
      response.set("Content-Type", "video/mp4");
      response.set("Accept-Ranges", "bytes");
      response.set(
        "Content-Length",
        imgData["ContentLength"]
      );
      response.set(
        "Content-Range",
        imgData["ContentRange"]
      );
      response.set("ETag", imgData["ETag"]);
      response.set(
        "Last-Modified",
        imgData["LastModified"]
      );
      response.status(code);
      response.send(imgData.Body);
    }
  });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user15575918