-1

I am trying to use angular httpClient to access npm registry to get specific package dependencies

When I am doing the request I am getting CORS error

Access to XMLHttpRequest at 'https://registry.npmjs.org/async/2.0.1' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. http://registry.npmjs.org/async/2.0.1

this.httpClient.get(requestUrl).pipe(catchError(this.handleError)).subscribe((result: any) => {
    console.log(result);
});`

Do I need to add headers to request in order of this to work?

Evaldas Buinauskas
  • 13,739
  • 11
  • 55
  • 107
Zakk
  • 758
  • 3
  • 11
  • 20
  • 1
    Possible duplicate of [XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header](https://stackoverflow.com/questions/35553500/xmlhttprequest-cannot-load-xxx-no-access-control-allow-origin-header) – Quentin Oct 28 '19 at 21:17

2 Answers2

3

You can use unpkg (https://unpkg.com/) instead of https://npmjs.com/

Unpkg is a CDN and allows to use fetch and XMLHttpRequest

vadzim
  • 481
  • 4
  • 7
-1

If developing locally, you can't change much in your code because npm registry will block anything called from localhost. To make this work, you could use CORS proxies, for instance https://cors-anywhere.herokuapp.com

So your request url would change to https://cors-anywhere.herokuapp.com/https://registry.npmjs.org/async/2.0.1

and you could change your code to something similar:

if(!environment.production) {
    const corsProxy = 'https://cors-anywhere.herokuapp.com/'
    requestUrl = `${corsProxy}${requestUrl}` 
}

this.httpClient.get(requestUrl).pipe(catchError(this.handleError)).subscribe((result: any) => {
    console.log(result);
});`
Evaldas Buinauskas
  • 13,739
  • 11
  • 55
  • 107
  • this issue here is that npm does not support CORS at all. the `if (!environment.production)` is a little misleading here, because this code will not in production either. – TBieniek Feb 20 '20 at 07:14