首页 文章

将标头传递到离子3中的请求时,HTTP GET无法读取属性'length'

提问于
浏览
0

我已经 Build 了一个离子3提供程序来获取我的数据 . 这是我在 rest.ts 的代码

getStats(): Observable<{}> {   
let headers = new HttpHeaders({'key': this.apiKey});
return this.http.get(this.apiUrl, {headers: headers});

}

我在 result.ts 文件中调用了这个方法 .

getStats(){
    this.rest.get().subscribe(stats => {
      console.log(stats);
    });
  }

我想在我的主页上绑定这些数据,但是当我运行应用程序时,我的控制台出现错误 .

无法读取未定义的属性“长度”

我使用了角度HTTP的官方文档 .

https://angular.io/guide/http

有人能指出我正确的方向吗?

更新:

key: string = '-1' 取代了apikey

错误:

对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头 . 因此不允许Origin'http:// localhost:8100'访问 . 响应具有HTTP状态代码404.core.js:1449 ERROR HttpErrorResponse {headers:HttpHeaders,status:0,statusText:“Unknown Error”,url:null,ok:false,...} error:ProgressEvent {isTrusted:true,lengthComputable :false,loaded:0,total:0,type:“error”,...} headers:HttpHeaders {normalizedNames:Map(0),lazyUpdate:null,headers:Map(0)} message:“Http失败响应(未知) url):0未知错误“name:”HttpErrorResponse“ok:false status:0 statusText:”Unknown Error“url:null proto:HttpResponseBase

1 回答

  • 0

    如果 HttpHeaders 对象中任何属性的值为 undefinednullHttpClient 将生成错误 Cannot read property 'length' of undefined . 您是否完全确定 HttpHeaders 在创建 HttpHeaders 对象时没有 undefinednull 值?尝试用空字符串 '' 替换 this.key 并查看错误是否仍然存在 .

    我在这个StackBlitz中重新创建了错误 . 检查控制台以查看错误 .

    我建议在密钥上设置一个默认值,以帮助避免此错误 . 显然不会作为有效API密钥传递的东西 .

    key: string = '-1';
    

    希望这有帮助!

相关问题