【问题标题】:Calling HTTPS API from Angular deployed in http server从部署在 http 服务器中的 Angular 调用 HTTPS API
【发布时间】:2022-01-20 05:01:22
【问题描述】:

我正在通过以下代码从部署在 http 服务器中的 Angular 服务调用 HTTPS API。

this.chatbotUrl = "https://something.com/api"; 
getDashBoardData(): Observable<any> {
    return this.http.get<IContainer>(this.chatbotUrl+"/chatbot/get-dashboard-data").pipe(
      map((response) => (response ? response : {})),
      catchError( this.handleError )
    );
  }

但是当我调用这个 API 时,我收到了这个错误,“https://something.com/api/chatbot/get-dashboard-data 的 Http 失败响应:0 未知错误”。下面的错误也是get。

GET https://something.com/api/chatbot/get-time-wise-traffic/7 net::ERR_CERT_COMMON_NAME_INVALID

如何从部署在 http 服务器中的 Angular 服务调用 https API?

【问题讨论】:

  • 如果您检查响应状态(如 422、400),这将有助于回答。我认为问题与 CORS 有关。
  • 此 API“something.com/api/chatbot/get-time-wise-traffic/7”是外部的。所以我认为与 CORS 相关没有问题,我认为
  • 该错误表明您尝试访问的服务器配置不正确。这是一个与 TLS 相关的错误。
  • 如何忽略 TLS 相关的错误?

标签: javascript angular rest http https


【解决方案1】:

我想你没有正确配置API,请检查网站是否需要任何密钥才能访问。这里我提供了我正在使用的API的component.ts文件和服务文件供你参考。 如果 CORS 错误,请尝试将 CORS 扩展添加到您的浏览器;否则清除缓存并再次运行您的代码。

组件.ts:

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { YoutubeService } from '../youtube.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  Name:any;
  details: any;
  info:any;
  display!:boolean;

  constructor(private service:YoutubeService,public sanitizer: DomSanitizer) { }
  
  ngOnInit(): void {
    this.service.GetVideos().subscribe((res:any)=> {
      this.info= res as any
      this.info=this.info.items;
      console.log(this.info);
      this.display=true
    });
   
  }
  onSubmit() {
    this.service.GetSearch(this.Name).subscribe(res=> {
        this.details= res as any
        this.details=this.details.items;
        // this.details.forEach((function.this.details.i) => {
        //    ele
        // });
        console.log(this.details);
        this.display=true
      });
      
  }

}

服务:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { GoogleLoginProvider } from 'angularx-social-login';

@Injectable({
  providedIn: 'root'
})
export class YoutubeService {
  private APIURL = "https://youtube.googleapis.com/youtube/v3/";
  private APIKEY ="AIzaSyB40HaKwd0VggftBq8R9sEwQx_NG5xOOWc";

  constructor(private http:HttpClient) { }
  public GetSearch(name:string)
  {
    console.log(name)
    return this.http.get(this.APIURL+"search?part=snippet&key="+this.APIKEY+"&q="+name+"&type=video");
  }

【讨论】:

    猜你喜欢
    • 2018-01-30
    • 2019-11-30
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    相关资源
    最近更新 更多