【发布时间】:2019-11-16 04:21:53
【问题描述】:
在我的应用程序中,我有一个 proxy.conf.json 文件来绕过 cors 策略。虽然现在控制台没有错误。返回结果似乎存在问题。当我知道响应在 itunes api 上有 50 个专辑时,它在我的 json 中给出了 0 个结果。
proxy.conf.json
{
"api": {
"target": "https://itunes.apple.com/search?term=drake",
"secure": true,
"changeOrigin": true
}
}
service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ApiService {
api: string = 'api';
constructor(
private http: HttpClient,
) { }
getAll(): Observable<any> {
return this.http.get<any>(this.api)
.pipe(
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.log(error.error.message)
} else {
console.log(error.status)
}
return throwError(
console.log('Something is wrong!'));
};
}
component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';
import { ApiService } from '../../../services/api.service';
@Component({
selector: 'app-content',
templateUrl: './content.component.html',
styleUrls: ['./content.component.scss']
})
export class ContentComponent implements OnInit {
public results = [];
public data = [];
constructor(private service: ApiService) { }
private http: HttpClient
ngOnInit() {
this.getApi();
}
private getApi() {
this.service.getAll().subscribe((results) => {
console.log('JSON Response = ', JSON.stringify(results));
this.data = results.results;
})
}
}
请出主意?
【问题讨论】:
-
为什么说是代理json问题
-
请在此处查看文档
https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/
标签: javascript angular typescript api proxy