【问题标题】:HttpClientModule http.get not workingHttpClientModule http.get 不工作
【发布时间】:2018-03-16 09:08:08
【问题描述】:

我拿起这个以前工作的应用程序 (Angular2),发现它现在不能正常工作 (Angular4)。

使用了模块(可能无关紧要):

import { HttpModule, JsonpModule } from '@angular/http';

正在使用的模块:

import { HttpClientModule} from '@angular/common/http';

尝试从后端(Node.js、Express 和 MongoDB)获取记录列表,如下所示。

    listResource(resType: string, parameters: string[]) {
    console.log("***listResource");
    let headers = new HttpHeaders().set("X-CustomHeader", "custom header value");

    headers.append('Content-Type', 'application/fhir+json');
    headers.append("'Access-Control-Allow-Origin", "*");
    headers.append("Accept", "application/fhir+json");
    headers.append("USER_KEY", "QIF83Fjoe4sYxdQsah3h"); //TOUCHSTONE KEY   

    let urlString = this.baseUrl + resType + "/list"; // + queryString;
    console.log("List resource URL string: [" + urlString + "]");
    return (this.httpClient.get(urlString, { headers })
        .map((res: Response) => res.json()))
        .catch((error: any) => Observable.throw(error.json().error || 'Server error from Observable http.get call')); //...errors if any
} 

当我的组件被加载时,上面的 listResource 将被调用如下。

  ngOnInit() {
    //Get the initial 25 latest patient
    //this.progressBar = true;
    this.currentPage = 0;
    this.patientList = [];
    this.globalSvc.gPatient = [];
    console.log("***OnInit");

    this.restSvc.listResource("Patient", ["identifier=*", "family=*", "given=*"]).subscribe(
      data => {
        console.log("Response data: " + JSON.stringify(data));
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.log('An error occurred:', err.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
      });
  }

以下是 Chrome 控制台的输出。当然,我没有得到任何好的回应。在我看来,Chrome 浏览器发送 CORS 选项并且服务器正确响应,然后浏览器没有发送实际的 GET。

如果我直接从没有 CORS 的 PostMan 发送 REST API 请求,我会从服务器获得预期的良好响应。因此,在我看来,服务器还可以。

问题:

  1. 知道如何调试或修复它吗?
  2. 这是否与 Angular 客户端和 Node.js 服务器上的 CORS 有关?
  3. ${err.status} 和 ${err.error} 在 Chrome 控制台中是“未定义的”。我怎样才能找到实际的错误?

    console.log(Backend returned code ${err.status}, body was: ${err.error});


更新 1 基于 Grey 对不可变标头和 const 的建议。 GET 现在正在返回数据。

【问题讨论】:

  • 1.我不明白为什么在函数中设置参数而不在您的请求中设置?这是一个错误,或者你可以在没有你的参数的情况下得到它。 2. 尝试只返回错误而不是 error.json().error。会发生什么?
  • 您好,罗马,感谢您的帮助。参数是用来构造查询字符串的,但为了清楚起见,我把它取出来了。让 urlString = this.baseUrl + resType + "/list"; // + 查询字符串;
  • 嗨罗马,再次感谢。我将代码更改为抛出错误 - .catch((error: any) => Observable.throw(error || 'Server error')。Chrome 控制台现在显示“后端返回代码 0,正文为:[object ProgressEvent]。它是'后端返回的代码未定义,正文是:未定义。

标签: node.js angular cors


【解决方案1】:

headers.append() 不会改变 headers,它会返回一个新的 Headers(因为 Headers 是不可变的)。

所以,而不是

let headers = new HttpHeaders().set("X-CustomHeader", "custom header value");
headers.append('Content-Type', 'application/fhir+json');
headers.append("'Access-Control-Allow-Origin", "*");
headers.append("Accept", "application/fhir+json");
headers.append("USER_KEY", "QIF83Fjoe4sYxdQsah3h"); //TOUCHSTONE KEY

您需要执行以下操作:

let headers = new HttpHeaders().set("X-CustomHeader", "custom header value")
  .append('Content-Type', 'application/fhir+json')
  .append("'Access-Control-Allow-Origin", "*")
  .append("Accept", "application/fhir+json")
  .append("USER_KEY", "QIF83Fjoe4sYxdQsah3h"); 

哦,那实际上应该是const headers =,而不是let headers =

【讨论】:

    猜你喜欢
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 2017-08-29
    相关资源
    最近更新 更多