Kay
Kay

Reputation: 19718

Angular CORS Issue When Making Multiple Requests Consecutively

i am using Angular 6 and i have a node api backend.

Iam getting a cors issue but it only happens occasionally.

Every 5 seconds i am doing a http get request

   const url = 'https://<removed>.com/api/v1/transactions/' + transactionId;

    interval(5000)
        .pipe(
            switchMap(() => this.httpClient.get(url)),
            tap((response: any) => {
                this.summary = response;
            }),
            takeWhile((response: any) => response.data['status'] !== 'Completed'),
    ).subscribe();

}

The first request is fine, then i get the following error on the next request.

Failed to load https://"".com/api/v1/transactions/f3debad2-a830-4168-9a03-475389dae7e0: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 502.

Cross-Origin Read Blocking (CORB) blocked cross-origin response https://"".com/api/v1/transactions/f3debad2-a830-4168-9a03-475389dae7e0 with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Again this only happens sometimes, other times i can make as many requests i want with 200 responses.

In my node backend i have, before all my routes.

this.app.use(cors());

Upvotes: 3

Views: 1034

Answers (1)

I'm not sure if this will solve your CORB issue. I added a timeout as a temporary fix for my CORB issue. My CORB issue appears if my http request takes too long to finish or if there's too many redirect

sample: If I make a multiple request to (http://www.redbull.com, http://www.redbull.org, http://www.redbull.net, and so on) other extension might redirect to .com and if takes too long I get the CORB error similar to yours

so what I did was I added timeout

// set request option
const requestOption = url => {
    return {
       url      : url,
       method   : 'HEAD',
       json     : true,
       timeout  : 5000,
       headers  : { 'connection': 'Keep-Alive' }
    }
}

// initialize request
const initializeRequest = (callback, option) => {
    request(option, (error, response, result) => {
      // for undefined response
      if(!response)
          return callback(null, response === undefined ? 404 : 200)

      callback(error, response.statusCode);
    }); 
}

// on your controller
module.exports.executeRequest = (req, res) => {
    //call initialize request here and create error handler.
    initializeRequest(your callback, requestOption(your URL));
}

Upvotes: 1

Related Questions