Angular4.x跨域请求
Angular4.x请求
码云地址:
https://gitee.com/ccsoftlucifer/Angular4Study
1. 搭建工程
新建一个工程angulardemo03
ng new angulardemo03
npm install 更新依赖
2. 新建组件
在app目录新建文件夹components,自己自定义的所有的组件都放在这个目录下面.
ng g component components/news
目录结构如下:

3.添加请求相关的model
编辑app.modle.ts
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
NewsComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
4.编写代码
news.component.html 编写一个按钮用来发送请求:
<h2>你好angular</h2>
<p>
news works!
</p> <br>
<button (click)="requestData()">请求数据</button>
从服务器拿到的值:
{{value}}
news.component.ts编写逻辑,导入http服务
import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {
public value:any
constructor(private http:HttpClient) { }
ngOnInit() {
// this.http.get('http://localhost:8080/user/findUser?id=1')
// .subscribe(res=>{ this.value = res })
}
//请求数据方法
requestData(){
console.log('请求数据');
var url='http://localhost:8080/user/findUser?id=1';//这里定义一个地址,要允许跨域
this.http.get(url).subscribe(function(data){
console.log(data);
},function(err){
console.log(err);
})
}
}
5.解决跨域
由于前端工程是localhost:4200,请求后端工程Localhost:8080,会出现跨域错误:
Access-Control-Allow-Origin' header is present on the requested resource.
解决办法:
5.1 在项目的根目录添加proxy.config.json文件
{
"/": {
"target": "http://localhost:8080/"
}
}
5.2修改package.json文件
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.config.json",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
5.3修改angular.json
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "angulardemo03:build",
"proxyConfig":"proxy.config.json"
},
"configurations": {
"production": {
"browserTarget": "angulardemo03:build:production"
}
}
},
5.4服务器端添加注解
@CrossOrigin(origins = "http://localhost:4200",allowCredentials = "true")
这样数据就拿过来了啦~

使用RxJS进行请求发送:
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent, SubscriptionLike, PartialObserver, concat } from 'rxjs';
import { map, filter, scan } from 'rxjs/operators';
import { webSocket } from 'rxjs/webSocket';
import { ajax } from 'rxjs/ajax';
import { TestScheduler } from 'rxjs/testing';
请求:
//另外一种请求方式
useRxJsRequestData(){
var _result=this;
console.log('请求数据');
if(this.inputValue==''){
//用户没有输入
alert('请先输入值');
}else{
//用户有输入的值
var url='http://localhost:8080/user/findUser?id='+this.inputValue;
this.http.get(url).subscribe(res =>{
console.log(res);
console.log(typeof(res));
console.log(res['id']);
var _this = this; _this.obj.id=res['id'];
_this.obj.useName=res['userName'];
_this.obj.password=res['password'];
_this.obj.age=res['age'];
})
//console.log(map);
}
}
Angular4.x跨域请求的更多相关文章
- Laravel中的ajax跨域请求
最近接触Laravel框架ajax跨域请求的过程中遇到一些问题,在这里做下总结. 一开始发起ajax请求一直报500错误,搜索相关资料后发现Laravel要允许跨域请求可以加入Cors中间件,代码如下 ...
- 跨域请求——WebClient通过get和post请求api
AJAX不可以实现跨域请求,经过特殊处理才行.一般后台可以通过WebClient实现跨域请求~ //get 请求 string url = string.Format("htt ...
- 原生js封装ajax,实现跨域请求
描述: 需要ajax跨域请求,用cors跨域方案.服务端设置: header('Access-Control-Allow-Origin: http://front.ls-la.me'); header ...
- 关于试用jquery的jsonp实现ajax跨域请求数据的问题
我们在开发过程中遇到要获取另一个系统数据时,就造成跨域问题,这就是下文要说的解决办法: 先我们熟悉下json和jsonp的区别: 使用AJAX就会不可避免的面临两个问题,第一个是AJAX以何种格式来交 ...
- 【JavaScript】--重点解析之跨域请求
JSON JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. JSON是用字符串来表示Javascript对象,例如可以在django中发送一个JSON格式 ...
- 利用CORS实现跨域请求(转载)
跨域请求一直是网页编程中的一个难题,在过去,绝大多数人都倾向于使用JSONP来解决这一问题.不过现在,我们可以考虑一下W3C中一项新的特性--CORS(Cross-Origin Resource Sh ...
- Ajax_05之跨域请求
1.跨域请求: Cross Domain Request:跨域名的HTTP请求,浏览器从某个域名下的资源访问了另一域名下的另一资源(协议.域名或是端口号不同): ①浏览器允许跨域请求的情形: < ...
- 浅谈linux 下,利用Nginx服务器代理实现ajax跨域请求。
ajax跨域请求对于前端开发者几乎在任何一个项目中都会用到,众所周知,跨域请求有三种方式: jsonp; XHR2 代理: jsonp: 这种应该是开发中是使用的最多的,最常见的跨域请求方法,其实aj ...
- 解决ajax跨域请求 (总结)
ajax跨域请求,目前已用几种方法实现: 1)用原生js的xhr对象实现. var url="http://freegeoip.net/json/" ...
随机推荐
- 无限极分类(adjacency list)的三种方式(迭代、递归、引用)
一般的分类树状结构有两种方式: 一种是adjacency list,也就是是id,parent id这中形式. 另一种是nested set,即左右值的形式. 左右值形式查询起来比较高效,无需递归等, ...
- Python 经典面试题汇总之框架篇
前端和框架 1.谈谈你对http协议的认识 浏览器本质,socket客户端遵循Http协议 HTTP协议本质:通过\r\n分割的规范,请求响应之后断开链接 ==> 短连接.无状态 具体: Htt ...
- python使用rabbitMQ介绍一(生产-消费者模式)
1 模式介绍 生产者-消费者模式是最简单的使用模式. 一个生产者P,给队列发送消息,一个消费者C来取队列的消息. 这里的队列长度不限,生产者和消费者都不用考虑队列的长度. 队列的模型图: 2 示例代码 ...
- jquery html() callback
通过JQuery的.html()函数我们可以非常方便地加载一段HTML到指定的元素中,例如给<div></div>中放入一组图片.问题是JQuery的.html()函数是同步的 ...
- Jquery消息提示插件toastr使用详解
toastr是一个基于jQuery简单.漂亮的消息提示插件,使用简单.方便,可以根据设置的超时时间自动消失. 1.使用很简单,首选引入toastr的js.css文件 html <script s ...
- Django入门之路
Web框架开发-Django基础之web应用,Http协议 web框架开发-web框架简介,wsgiref模块,DIY一个web框架 web框架开发-Django简介 web框架开发-静态文件配置 w ...
- 014_zk路径过滤分析
一.线上zk访问延迟特别高需要统计一段时间内的zk写入路径top10,实现如下: #!/usr/bin/env python # -*- coding:utf-8 -*- import re,trac ...
- 云计算openstack介绍
一.云计算的前世今生 所有的新事物都不是突然冒出来的,都有前世和今生.云计算也是IT技术不断发展的产物. 要理解云计算,需要对IT系统架构的发展过程有所认识. 请看下 IT系统架构的发展到目前为止大致 ...
- AWS Step Function Serverless Applications
Installing VS Components To follow along with this article, you must have an AWS account and install ...
- 【CTSC2016】时空旅行
链接 http://uoj.ac/problem/198 题解 首先要发现答案要我们求这个式子: \[ ans=min\bigl((x_i-x)^2+c_i\bigr) \] 显而易见的是这种时空嫁接 ...