Angular4.x跨域请求
Posted battlecry
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
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")
这样数据就拿过来了啦~
以上是关于Angular4.x跨域请求的主要内容,如果未能解决你的问题,请参考以下文章
Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段