简体   繁体   English

proxy.conf.json 在 Angular 中无法按预期工作 6

[英]proxy.conf.json not working as expected in Angular 6

In my application I have a proxy.conf.json file to get around cors policy.在我的应用程序中,我有一个 proxy.conf.json 文件来绕过 cors 策略。 Although there is no error for the console now.虽然现在控制台没有错误。 There seems to be an issue with returning the result.返回结果似乎存在问题。 It gives my a 0 results in my json when I know the response has 50 albums on the itunes api.当我知道响应在 iTunes api 上有 50 张专辑时,它在我的 json 中给出了 0 结果。

proxy.conf.json proxy.conf.json

{
    "api": {
      "target": "https://itunes.apple.com/search?term=drake",
      "secure": true,
      "changeOrigin": true
    }
}

service.ts服务.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组件.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;
    })
  }
}

ideas please?请问有什么想法吗?

Have you tried with /api intead of just api ?您是否尝试过使用/apiapi

{
  "/api": {
    "target": {
      "host": "itunes.apple.com/search?term=drake"",
      "protocol": "https",
      "port": xxx
    },
    "secure": false,
    "changeOrigin": true
    "pathRewrite": {
      "^/api": ""
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM