加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS 与 server 通信

发布时间:2020-12-17 08:44:12 所属栏目:安全 来源:网络整理
导读:一、搭建AngularJS 框架 详细过程请参考官网教程:https://angular.io/guide/quickstart 在上面的截图中出现了两个错误提示: 1. ng server --open 是启动angular 需要在项目目录下执行,而我是在IdeaProjects根目录下执行的,所以报错 2. 第二个错误是因为

一、搭建AngularJS 框架

详细过程请参考官网教程:https://angular.io/guide/quickstart


在上面的截图中出现了两个错误提示:

1. ng server --open 是启动angular 需要在项目目录下执行,而我是在IdeaProjects根目录下执行的,所以报错

2. 第二个错误是因为我启动了其他angular项目,导致端口被占用,关掉其他项目就释放了4200端口,当然也可以在程序中修改端口号


启动成功以后,浏览器会弹出相应的欢迎页面


二、与server 端进行通信

1. 在src-->app-->app.component.html 文件中接受server端返回的数据

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{title}}!
  </h1>
</div>
<h2>
  From tomcat {{data._body}}
</h2>
2.在src-->app-->app.component.ts 文件中配置HTTP请求
import {Component,OnInit} from '@angular/core';
import {Http} from '@angular/http';

@Component({
  selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  data: any;
  title = 'app';
  constructor(private _http: Http) {
  }
  ngOnInit(): void {
    this.data = this._http.get('de/control/test')
      .subscribe(data => {
        this.data = data;
        console.log(this.data._body);
      });
  }
}

现在打开浏览器,会发现有错误


3. 在app.moudule.ts中引入HTTP模块

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import {HttpModule} from '@angular/http';

@NgModule({
  declarations: [
    AppComponent
  ],imports: [
    HttpModule,// 引入HTTP模块
    BrowserModule
  ],providers: [],bootstrap: [AppComponent]
})
export class AppModule { }
打开浏览器发现get请求中的端口不对

4. 我们在当前项目目录下新建proxy.conf.json

{
"/de" : {
"target" : "http://localhost:8081","secure" : false
}
}
在终端运行 ng serve --proxy-config proxy.conf.json 所有以de开头的URL请求都会发送到target



5.启动server端的服务


6.打开浏览器,服务端成功返回结果Hello CUEB!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读