首页 > 解决方案 > 项目部署被 CORS 策略阻止

问题描述

我想使用 Ionic 部署 PWD,但我无法与API通信以返回请求的信息。

我认为这个问题是为了通过 HTTP 请求访问的安全性。

在此处输入图像描述

我的服务代码:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ResponseTopHeadlines } from '../models/models';
import { environment } from 'src/environments/environment';

const apiAkey = environment.apiKey;
const apiUrl = environment.apiUrl;

const headers = new HttpHeaders({
  'X-Api-Key': apiAkey,
});

@Injectable({
  providedIn: 'root',
})
export class NewsService {
  headLinesPage = 0;
  categoryAct = '';
  categoryPg = 0;

  constructor(private http: HttpClient) {}

  private startQuery<T>(query: string) {
    query = apiUrl + query;
    return this.http.get<T>(query, { headers });
  }

  getTopHeadLines() {
    this.headLinesPage++;
    return this.startQuery<ResponseTopHeadlines>(
        `/top-headlines?country=us&page=${this.headLinesPage}`,
    );
  }

  getTopHeadLinesCategory(category: string) {
    if (this.categoryAct === category) {
        this.categoryPg++;
    } else {
          this.categoryPg = 1;
          this.categoryAct = category;
     }
     return this.startQuery<ResponseTopHeadlines>(
       `/top-headlines?country=us&category=${category}&page=${this.categoryPg}`,
     );
  }
}

标签: angularionic-frameworkrequestxmlhttprequest

解决方案


推荐阅读