简体   繁体   English

使用Angular 5 HttpClient获取数据

[英]Fetching data using Angular 5 HttpClient

I am trying to load data from a rest endpoint using the HttpClient provided by Angular. 我正在尝试使用Angular提供的HttpClient从其余端点加载数据。 The endpoint in question uses a token to authorize the user. 有问题的端点使用令牌来授权用户。

    getData() {
     if (this.token) {
        const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type':  'application/json',
          'Authorization': 'Bearer' + ' ' + this.token
       })
     };
     this.http.get('https://some url', httpOptions).subscribe((res) => {
       console.log(res);
     }, (error) => {
       console.log(error);
     });
     } else {
       this.empty_token = true;
     }
   }

I get the following error while trying to do that: Response for preflight has invalid HTTP status code 401. 尝试执行此操作时出现以下错误: 飞行前响应具有无效的HTTP状态代码401。

However, the same code works for a some demo url that works on "http" and not for "https" . 但是,相同的代码适用于某些演示网址,该网址适用于“ http”而不适用于“ https”

I tried using the same by making a request using Postman or any other RestClient for that matter and it works fine. 我试图通过使用邮递员或任何其他RestClient发出请求来使用相同的东西,并且效果很好。

If the calling url is http it is normal that it does not work. 如果调用的URL是http,则无法正常工作。 This could help you https://angular.io/api/platform-browser/DomSanitizer 这可以帮助您https://angular.io/api/platform-b​​rowser/DomSanitizer

Or try this 或者试试这个

private httpOptions = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer ' + this.token});

you should add 您应该添加

"proxies": [
    {
      "path": "/v1",
      "proxyUrl": "'https://some url'"
    }

to your project . 到你的项目。

you can look to this link https://github.com/mgechev/angular-seed/wiki/Add-a-Proxy-to-browsersync 您可以查看此链接https://github.com/mgechev/angular-seed/wiki/Add-a-Proxy-to-browsersync

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

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