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
三、利用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
启动代理不生效
七、一个完整的项目案例
2 0
- Angular开发(十四)-利用angular的http转发、即代理http 请求,处理项目中请求跨域的问题
- Angular学习:http请求失败的问题
- angular的http请求方式
- $http——ajax跨域请求的angular方式
- angular的http请求本地文件出现跨域提醒
- angular的http三种请求方式
- Angular开发(十六)-HTTP请求的详细介绍
- Angular----$http请求数据
- r.js压缩angular项目,Angular+requirejs+rjs实现初始化http请求数的优化
- Angular 的 $http 跨域的问题
- angular的$http的ajax的请求操作
- angular用$http请求数据
- angular中的http请求封装
- angular的http请求需要注意的地方
- angular 取消或终止$http的ajax请求
- ajax请求和angular js中http请求
- HTTP中请求与转发的细节
- 基于angular-cli配置代理解决跨域请求问题
- Java面试之前复习总结(一)
- ssh的基本原理哦
- C++获取时间的问题
- MyBatis框架的学习(七)——MyBatis逆向工程自动生成代码
- Torch 的安装与基本用法
- Angular开发(十四)-利用angular的http转发、即代理http 请求,处理项目中请求跨域的问题
- Java网络通信之Socket编程
- VIM 配置 ctags
- Linux 的dhcp启动异常之No subnet declaration for eth1 (192.168.48.134)
- 认识端口与计算机入侵防范
- Android 5.X SVG矢量动画机制——Android群英传
- 将you are from shanghai 以shanghai from are you的形式输出
- 为什么每个人都这样匆忙?
- flex弹性布局