Angular4.x跨域請求

Angular4.x請求

碼雲地址:css

https://gitee.com/ccsoftlucifer/Angular4Studyhtml

1. 搭建工程

新建一個工程angulardemo03前端

ng new angulardemo03git

npm install 更新依賴web

2. 新建組件

在app目錄新建文件夾components,本身自定義的全部的組件都放在這個目錄下面.ajax

ng g component components/newsnpm

目錄結構以下:json

3.添加請求相關的modelbootstrap

編輯app.modle.ts後端

1 import { HttpClientModule  } from '@angular/common/http'; 
 1 @NgModule({
 2   declarations: [
 3     AppComponent,
 4     NewsComponent
 5   ],
 6   imports: [
 7     BrowserModule,
 8     AppRoutingModule,
 9     HttpClientModule
10   ],
11   providers: [],
12   bootstrap: [AppComponent]
13 })

4.編寫代碼

news.component.html 編寫一個按鈕用來發送請求:

<h2>你好angular</h2>
<p>
  news works!
</p>

<br>
<button (click)="requestData()">請求數據</button>
從服務器拿到的值:
{{value}}

news.component.ts編寫邏輯,導入http服務

 1 import { Component, OnInit } from '@angular/core';
 2 
 3 import {HttpClient} from '@angular/common/http';
 4 @Component({
 5   selector: 'app-news',
 6   templateUrl: './news.component.html',
 7   styleUrls: ['./news.component.css']
 8 })
 9 export class NewsComponent implements OnInit {
10   public value:any
11   constructor(private http:HttpClient) { }
12 
13   ngOnInit() {
14     // this.http.get('http://localhost:8080/user/findUser?id=1')
15     //  .subscribe(res=>{ this.value = res })
16 
17   }
18   //請求數據方法
19   requestData(){
20     console.log('請求數據');
21     var url='http://localhost:8080/user/findUser?id=1';//這裏定義一個地址,要容許跨域
22     this.http.get(url).subscribe(function(data){
23       console.log(data);
24     },function(err){
25       console.log(err);
26     })
27   }
28 
29 }

5.解決跨域

  因爲前端工程是localhost:4200,請求後端工程Localhost:8080,會出現跨域錯誤:

  Access-Control-Allow-Origin' header is present on the requested resource.

  解決辦法:

  5.1 在項目的根目錄添加proxy.config.json文件

  

1 {
2     "/": {
3         "target": "http://localhost:8080/"
4     }
5 }

  5.2修改package.json文件

1 "scripts": {
2     "ng": "ng",
3     "start": "ng serve --proxy-config proxy.config.json",
4     "build": "ng build",
5     "test": "ng test",
6     "lint": "ng lint",
7     "e2e": "ng e2e"
8   },

  5.3修改angular.json

 1 "serve": {
 2           "builder": "@angular-devkit/build-angular:dev-server",
 3           "options": {
 4             "browserTarget": "angulardemo03:build",
 5             "proxyConfig":"proxy.config.json"
 6           },
 7           "configurations": {
 8             "production": {
 9               "browserTarget": "angulardemo03:build:production"
10             }
11           }
12         },

  5.4服務器端添加註解

1  @CrossOrigin(origins = "http://localhost:4200",allowCredentials = "true")

  

這樣數據就拿過來了啦~

 

 

 

  使用RxJS進行請求發送:

1 import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent,  SubscriptionLike, PartialObserver, concat } from 'rxjs';
2 import { map, filter, scan } from 'rxjs/operators';
3 import { webSocket } from 'rxjs/webSocket';
4 import { ajax } from 'rxjs/ajax';
5 import { TestScheduler } from 'rxjs/testing';

 

  請求:

 1 //另一種請求方式
 2     useRxJsRequestData(){
 3       var _result=this;
 4       console.log('請求數據');
 5       if(this.inputValue==''){
 6           //用戶沒有輸入
 7           alert('請先輸入值');
 8       }else{
 9           //用戶有輸入的值
10           var url='http://localhost:8080/user/findUser?id='+this.inputValue;
11           this.http.get(url).subscribe(res =>{
12             console.log(res);
13             console.log(typeof(res));
14             console.log(res['id']);
15             var _this = this;
16             
17            _this.obj.id=res['id'];
18             _this.obj.useName=res['userName'];
19             _this.obj.password=res['password'];
20             _this.obj.age=res['age'];
21           })
22          //console.log(map);
23       }
24     }
相關文章
相關標籤/搜索