利用angular的http轉發、即代理http 請求,處理項目中請求跨域的問題

1、在項目的根目錄下建立一個proxy.conf.json文件,文件所在位置如圖 這裏寫圖片描述

文件代碼css

{
    "**": {
        "target": "http://localhost:8000", // 指向須要代理的api地址
        "secure":false
    }
}

2、修改package.json文件

ng serve --proxy-config proxy.conf.json
1
這裏寫圖片描述html

3、利用nodejs的express框架建立一個後端服務

> const express = require("express");
> 
> const app = express();
> 
> let dataSet = [
>     {"id":"0","name":"張三","age":20},
>     {"id":"1","name":"李四","age":34},
>     {"id":"2","name":"王五","age":30},
>     {"id":"3","name":"馬六","age":50} ]; app.get("/products",(req,res)=>{
>     res.json(dataSet); });
> 
> app.listen(8000,"localhost",()=>console.log("服務已經啓動"))

4、案例demo代碼

//ts文件
import {Component, OnInit} from '@angular/core';
import {Observable} from "rxjs/Observable";
import {Http} from "@angular/http";
import "rxjs/Rx";

@Component({
  selector: 'app-httpdemo',
  templateUrl: './httpdemo.component.html',
  styleUrls: ['./httpdemo.component.css']
})
export class HttpdemoComponent implements OnInit {
  dataSource: Observable<any>;
  dataSet: Array<any> = [];

  constructor(private http: Http) {
    this.dataSource = this.http.get("/products").map((res) => res.json());
  }

  ngOnInit() {
    this.dataSource.subscribe(
      (data) => this.dataSet = data
    )
  }

}
//html代碼
<ul>
  <li *ngFor="let item of dataSet">{{item.name}}--{{item.age}}</li>
</ul>

5、運行效果 這裏寫圖片描述

6、重要說明:啓動服務的時候必須用npm run start啓動,代理才生效,若是用ng serve啓動代理不生效

相關文章
相關標籤/搜索