1. 程式人生 > >angular4使用httpclient時解決跨域問題

angular4使用httpclient時解決跨域問題

clas 內容 header host ble 重新 官方 cor table

跨域問題的環境:

在本地開發時,使用命令行ng s開啟服務,訪問地址為http://localhost:4200

假設調用數據接口的服務地址為http://localhost:8088/api/data.action

解決跨域問題的方法:

在angular4項目根目錄下創建文件proxy.config.json,文件內容為:

{
  "/api":{
    "target":"http://localhost:8088"
  }
}

那麽使用命令行 ng s --proxy-config proxy.config.json重新開啟服務後,就把接口服務代理過來了,就可以使用

http://localhost:4200/api/data.action來請求接口服務了,那麽問題就迎刃而解了,因為現在不跨域了。

網上很多人問為啥用這種辦法還是解決不了,那是因為開啟服務的方法不對,要加參數,註意我上面標紅的地方。

使用httpclient請求數據的相關代碼:

hero.service.ts

import { Injectable } from ‘@angular/core‘;

import { Observable, of } from ‘rxjs‘;
import { HttpClient, HttpHeaders } from ‘@angular/common/http‘;
 
import { Hero } from ‘../data/hero‘;

@Injectable({
  providedIn: 
‘root‘ }) export class HeroService { constructor(private http: HttpClient) { } getHeroes(): Observable<Hero[]> { return this.http.get<Hero[]>("/api/data.action"); } }

我給的代碼並不完整,這些並不重要,只看標紅的部分就夠了,這個示例是根據官方的例子改的。

angular4使用httpclient時解決跨域問題