Angular6-proxy.config.json實(shí)現(xiàn)跨域

需求場景:

獲取后端api接口數(shù)據(jù),需要跨域。有時(shí),后臺(tái)可能有多個(gè)業(yè)務(wù),提供不同的API,為了方便管理,需要我們在一個(gè)文件里配置好。這樣,以后要更改接口時(shí)就很方便了。

解決方案

  • 建立本地代理proxy.config.json文件:

    angular6項(xiàng)目里新建proxy.config.json文件 ,放在根目錄,proxy.config.json(文件名可以隨便取,但建議統(tǒng)一)配置內(nèi)容,可參考:here。由于angular集成了webpack,所以你也可以研究webpack

    {
    "/apidata":{
        "target":"http://xxxxx:8093",
        "secure":false,
        "logLevel":"debug",
        "changeOrigin":true,
        "pathRewrite":{
        "^/apidata":""
            }
        }
    }
    

    這里定義的/apidata就是路由匹配規(guī)則 遇到這個(gè)開始解析 ,并且跟pathRewrite 定義的要一致target 設(shè)置的就是跨域域名端口。

  • angular.json配置文件加載配置代理文件proxy.config.json:

    angular.json文件中使用上面的配置文件(添加"proxyConfig":"proxy.config.json")

    "serve": {
        "builder": "@angular-devkit/build-angular:dev-server",
        "options": {
        "browserTarget": "appname:build",
        "proxyConfig":"proxy.config.json"
    },
    
    
  • 服務(wù)文件里使用http.get獲取接口數(shù)據(jù),url地址需要配置上代理重寫規(guī)則的 /apidata

    • 命令行建立服務(wù): ng g s 服務(wù)名
    • import HttpClient
    • contructor 定義http參數(shù): constructor(private http: HttpClient)
    • 使用HttpClient獲取遠(yuǎn)程服務(wù)器接口數(shù)據(jù),地址就前面加上代理文件的匹配/apidata ,后面在接上正確的地址,subcribe后面輸出數(shù)據(jù)
      import {Injectable, OnInit} from '@angular/core'
      import {HttpClient} from '@angular/common/http'
    
      @Injectable({
          providedIn: 'root'
      })
      
      export class DataService implement OnInit {
    
          constructor(private http: HttpClient) {}
    
          getData() {
              this.http.get('apidata/api/index').subscribe(
                  data => data // 此處可以做數(shù)據(jù)轉(zhuǎn)換、清洗
              )
          }
    
          ngOnInit() {}
      }
    
  • 組建內(nèi)調(diào)用服務(wù)獲取數(shù)據(jù)

      import { Component, OnInit } from '@angular/core';
      import { DataService } from '../data.service';
    
      @Component({
      selector: 'app-data',
      templateUrl: './data.component.html',
      styleUrls: ['./data.component.css']
      })
      export class DataComponent implements OnInit {
    
          constructor(private dataservice:DataService) { }
          ngOnInit() {
              this.dataservice.getData();
          }
      }
    
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容