Promise.all get 'Access-Control-Allow-Origin&#

2020-05-08 06:58发布

How are you. I found something strange problem. I am going to get 20 persons random info from 'https://randomuser.me/api/' So I implemented code as follow. then it show me 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 503. error.

    for (let i = 0; i < 20; i++) {
      const promise = this.http.get<any>('https://randomuser.me/api/').toPromise();
      promises.push(promise);
    }
    Promise.all(promises).then(function(values) {
      console.log(values);
    });

And what the strange thing is, if I get for under 4 persons data it doesn't happen. So following example work correctly.

    for (let i = 0; i < 4; i++) {
      const promise = this.http.get<any>('https://randomuser.me/api/').toPromise();
      promises.push(promise);
    }

It's very strange, I tried with Rxjs, using forkjoin operator, but result was same, it also only allowed for 4 observables. Please help me. Thank you.

1条回答
够拽才男人
2楼-- · 2020-05-08 07:46

Making my comments into an answer:

The 503 error status likely indicates something else is happening on the server that is getting falsely reported as a CORS error. Perhaps you are making too many requests of the server too quickly and it reports an error on an OPTIONS request for this reason and thus it gets reported as a CORS error, but really it's caused by making requests too quickly.

The generic reason for a 503 status code is "service unavailable". So this could also be caused by some infrastructure that protects the target server from too many requests.

As I can't modify api, how can I get 20 persons info? Do I have to use timer? or Recursive function? Both of them seems to be not so good solution. How can I solve this on Frontend side?

Read the doc on the API or visit the support forums and find out what kind of rate limiting it implements. If you can't find any doc or support info on that, then you will have to figure it out by testing and then limit your request rate to stay below that.


UPDATE

It appears from the doc that you can fetch 20 users with one API call.

See https://randomuser.me/documentation#multiple for details.

Example:

https://randomuser.me/api/?results=20
查看更多
登录 后发表回答