proxy.conf.json在Angular 6中无法按预期工作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了proxy.conf.json在Angular 6中无法按预期工作相关的知识,希望对你有一定的参考价值。
在我的应用程序中,我有一个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;
})
}
}
请提供想法?
答案
您是否尝试过仅使用/api
的api
intead?
{
"/api": {
"target": {
"host": "itunes.apple.com/search?term=drake"",
"protocol": "https",
"port": xxx
},
"secure": false,
"changeOrigin": true
"pathRewrite": {
"^/api": ""
}
}
}
以上是关于proxy.conf.json在Angular 6中无法按预期工作的主要内容,如果未能解决你的问题,请参考以下文章
如何在 proxy.conf.json 或 proxy.conf.js 中动态定义端口
angular package.json中start build
如何使用 proxy-config 将 Angular 2 应用程序部署到 HTTP 服务器