利用angular的http转发、即代理http 请求,处理项目中请求跨域的问题

发布时间:2019-06-26 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了利用angular的http转发、即代理http 请求,处理项目中请求跨域的问题脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

一、在项目的根目录下创建一个Proxy.conf.json文件,文件所在位置如图 这里写图片描述

文件代码

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

二、修改package.json文件

ng serve --PRoxy-config proxy.conf.json
1
这里写图片描述

三、利用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("服务已经启动"))

四、案例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>

五、运行效果 这里写图片描述

六、重要说明:启动服务的时候必须用npm run start启动,代理才生效,如果用ng serve启动代理不生效

脚本宝典总结

以上是脚本宝典为你收集整理的利用angular的http转发、即代理http 请求,处理项目中请求跨域的问题全部内容,希望文章能够帮你解决利用angular的http转发、即代理http 请求,处理项目中请求跨域的问题所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。