使用 angular httpClient 获取 npm 注册表导致 CORS
fetching npm registry with angular httpClient causing CORS
我正在尝试使用 angular httpClient 访问 npm 注册表以获取特定的包依赖项
当我执行请求时出现 CORS 错误
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);
});`
我是否需要在请求中添加 headers 才能正常工作?
如果在本地开发,则不能对代码进行太多更改,因为 npm registry 会阻止从本地主机调用的任何内容。为了使这项工作有效,您可以使用 CORS 代理,例如 https://cors-anywhere.herokuapp.com
因此您的请求 url 将更改为 https://cors-anywhere.herokuapp.com/https://registry.npmjs.org/async/2.0.1
您可以将代码更改为类似的内容:
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);
});`
您可以使用 unpkg (https://unpkg.com/) instead of https://npmjs.com/
Unpkg 是一个 CDN,允许使用 fetch
和 XMLHttpRequest
我正在尝试使用 angular httpClient 访问 npm 注册表以获取特定的包依赖项
当我执行请求时出现 CORS 错误
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);
});`
我是否需要在请求中添加 headers 才能正常工作?
如果在本地开发,则不能对代码进行太多更改,因为 npm registry 会阻止从本地主机调用的任何内容。为了使这项工作有效,您可以使用 CORS 代理,例如 https://cors-anywhere.herokuapp.com
因此您的请求 url 将更改为 https://cors-anywhere.herokuapp.com/https://registry.npmjs.org/async/2.0.1
您可以将代码更改为类似的内容:
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);
});`
您可以使用 unpkg (https://unpkg.com/) instead of https://npmjs.com/
Unpkg 是一个 CDN,允许使用 fetch
和 XMLHttpRequest