HTTP range request doesn't work if the start r

2019-08-24 05:57发布

问题:

Here is a simple demo that illustrates my question: https://funnyballoon.github.io/.

I am building a website whose data is based on randomly selected objects out of an array of JSON object (Loading random objects from a huge (>200MB) array file without loading the entire array), and I store that array as a static file hosted on Github. My website uses Angular. Now I am trying to use HTTP range request (https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests) to achieve such random selection. This is the method I use:

  getPartialText(){
  let path:string='/mock/mockData.json';
  let headers = new HttpHeaders().set('Range', 'bytes=0-123').set('Access-Control-Allow-Origin','*');
  this.http.get(path,{headers:headers, responseType: 'text'}).subscribe((data:any)=>{
    this.secondPartialText=data;
  });
}

Note here I set the bytes to '0-123', and this works perfectly, therefore it's (likely) not a CORS issue. However, when I set the start of the byte range to any number other than 0, for instance, 'bytes=1-123', I get an error with this message:

Http failure response for (unknown url): 0 Unknown Error

This is very confusing. Here is a simple demonstration of my website: https://funnyballoon.github.io/. As you can see, if you click the first button everything works just fine, whereas when you click the second button there's an error from the log.

Here is my code:

app.component.ts

import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public firstPartialText;
  public secondPartialText;

  constructor(public http: HttpClient){}

  getFirstPartialText(){
      let path:string='/mock/mockData.json';
      let headers = new HttpHeaders().set('Range', 'bytes=0-123').set('Access-Control-Allow-Origin','*');
      this.http.get(path,{headers:headers,responseType: 'text'}).subscribe((data:any)=>{
      this.firstPartialText=data;
      });}

  getSecondPartialText(){
      let path:string='/mock/mockData.json';
      let headers = new HttpHeaders().set('Range', 'bytes=1-123').set('Access-Control-Allow-Origin','*');
      this.http.get(path,{headers:headers, responseType: 'text'}).subscribe((data:any)=>{
      this.secondPartialText=data;
  });}
}

app.component.html

<div> <button (click)="getFirstPartialText()">Get First</button>      
  {{firstPartialText}}</div>

<div> <button (click)="getSecondPartialText()">Get Second</button>     
  {{secondPartialText}}</div>

I appreciate if anybody can point out what is going wrong here. Thanks!