Angular4.x跨域请求

时间:2023-03-09 14:32:22
Angular4.x跨域请求

Angular4.x请求

码云地址:

https://gitee.com/ccsoftlucifer/Angular4Study

1. 搭建工程

新建一个工程angulardemo03

ng new angulardemo03

npm install 更新依赖

2. 新建组件

在app目录新建文件夹components,自己自定义的所有的组件都放在这个目录下面.

ng g component components/news

目录结构如下:

Angular4.x跨域请求

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")

  

这样数据就拿过来了啦~

Angular4.x跨域请求

  使用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);
}
}