angular6 本地代理 跨域設置


 

需求場景:

本地前端angular6 獲取后端api接口數據

前端使用:angular 6

后端:thinkphp 5

解決方案

1)建立本地代理proxyconfig.json文件

angular6項目里新建proxyconfig.json文件 ,放在根目錄

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

}
}

 這里定義的/apidata就是路由匹配規則 遇到這個開始解析 ,並且跟pathRewrite 定義的要一致

target 設置的就是跨域域名端口

 

 

2)angular.json配置文件加載配置代理文件proxyconfig.json

然后在angular.json文件中使用上面的配置文件

"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "project1:build",
"proxyConfig":"proxyconfig.json"
},

添加 

 "proxyConfig":"proxyconfig.json"

找到serve配置 是在建立的項目下的,具體比如

 

目錄位置

 

3.服務文件里使用http.get獲取接口數據,url地址需要配置上代理重寫規則的  /apidata

命令行建立服務:

ng g s 服務名

①import httpClient

②contructor 定義http參數

③使用httpClient獲取遠程服務器接口數據,地址就前面加上代理文件的匹配/apidata ,后面在接上正確的地址,subcribe后面輸出數據

 

4)組建內調用服務獲取數據

ngOnInit() {
this.navservice.getnavdata();

}

import { Component, OnInit } from '@angular/core';

import { NavService } from '../nav.service';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {


  constructor(private navservice:NavService) { }

  ngOnInit() {
    this.navservice.getnavdata();

  }

}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM