Angular开发(十四)-利用angular的http转发、即代理http 请求,处理项目中请求跨域的问题

来源:互联网 发布:中国产业数据 编辑:程序博客网 时间:2024/05/21 09:38

虽然angular的http请求中提供了jsonp处理跨域问题,但是不常用,我们web服务器端可能会选择别的方式处理

  • web服务器端使用nginx进行反向代理处理
  • 使用nodejs中node-http-proxy解决本地开发ajax跨域问题
  • 使用angular自身的http转发,代理http请求

前面两种在本章节中就不去介绍,现在我只介绍第三种方式

一、在项目的根目录下创建一个proxy.conf.json文件,文件所在位置如图

这里写图片描述

  • 文件代码
{    "**": {        "target": "http://localhost:8000", // 指向需要代理的api地址        "secure":false    }}

二、修改package.json文件

ng serve --proxy-config proxy.conf.json

这里写图片描述

三、利用nodejsexpress框架创建一个后端服务

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启动代理不生效

七、一个完整的项目案例

2 0