与服务器通讯
- 创建web服务器,使用nodejs创建服务器,创建server文件夹,在这个文件夹中使用npm命令初始化,会创建一个包含默认配置的package.json文件,
npm init -y
- 需要使用typescript开发服务器,所以要引入node的类型定义文件,作用是让开发者可以再ts中使用现在已有的js写成的库
npm i @types/node –save
- 但是node本身是不能识别typescript的,所以需要将其编译成js,想要执行编译需要些一个配置文件tsconfig.json
目标是将其编译成es5规范的脚本,模块的规范是commonjs
"emitDecoratorMetadata": true,
"experimentalDecorators": true,与装饰器相关,编译时保留装饰器的原数据
"outDir": "build",编译完成后将js文件放入build目录中
"lib": ["es6"],表示开发时使用es6 语法
编译的时候排除node_modules目录下的文件
"exclude": [
"node_modules"
]
- 在项目下新建一个server目录,新建一个hello_server的ts文件,监听8000端口,收到请求后打出一个hello node
import * as http from 'http'
const server = http.createServer((request,response)=>{
response.end("hello node");
});
server .listen(8000);
- 启用服务器
node build/hello_server.js
- 使用Express创建restful的http服务,为了简化开发,安装express框架
npm i express --save
- express框架提供了所有应用都需要的一些常用功能,安装express的类型定义文件,使用ts 进行开发
npm i @types/express --save
- 在server目录下新建一个新的服务器配置文件auction_server.ts
import * as express from 'express'
const app = express();
app.get('/',(req,res)=>{
res.send("hello express");
});
app.get('/products',(req,res)=>{
res.send("接收到商品查询请求");
});
const server =app.listen(8000,"localhost",()=>{
console.log("服务器已启动")
})
- 在node服务器启动以后,如果服务器文件发生变化node不会自动加载变化的文件,只能重启node服务器才能显示变更
- 安装一个node工具,会监控node的源代码,当代码改变时会自动重启node服务器并加载最新的代码
npm i -g nodemon
- 使用这个工具的命令
nodemon build/auction_server.js
- 返回一个json格式的数据,直接从之前的项目中获得商品的定义文件Product类,继续获取商品的数据Product数组
- 在接收product请求时使用json方法,将products数组以json格式返回
app.get('/products',(req,res)=>{
res.json(products);
});
- 根据商品的id返回对应的商品信息
app.get('/product/:id',(req,res)=>{
res.json(products.find((product)=>product.id==req.params.id));
});
http通讯
- angular的http服务,获取商品的信息,但是在没有指定的情况下get的地址都是当前的相对地址,因此并不能获得数据,会报错
export class ProductComponent implements OnInit {
dataSource:Observable<any>;
products:Array<any>=[];
constructor(private http:Http) {
this.dataSource=this.http.get('/products')
.map((res)=>res.json());
}
ngOnInit() {
this.dataSource.subscribe(
(data)=>this.products=data
);
}
}
- 新建一个proxy.conf.json 文件,加入需要的配置,以便能从8000端口获取数据
{
"/api": {
"target": "http://localhost:8000"
}
}
- 修改package.json的配置,将刚配置的文件加入到启动信息中
"start": "ng serve --proxy-config proxy.conf.json",
- 因为指定以/api开始的地址才会访问8000端口,将本项目中product组件需要get请求的地址和node服务器端的地址之前加上一个/api
- http请求的发送并不是由get方法触发的,而是由subscribe方法触发的
- angular还提供另一种方法使用管道来触发这个流
<div>商品详情</div>
<ul>
<li *ngFor="let product of products | async">{{product.title}}</li>
</ul>
export class ProductComponent implements OnInit {
products:Observable<any>;
constructor(private http:Http) {
this.products=this.http.get('/api/products')
.map((res)=>res.json());
}
ngOnInit() {
}
}
- 发送http请求时带上请求头,可以用于作身份验证
constructor(private http:Http) {
let myHeaders=new Headers();
myHeaders.append("Authorization","Basic 123456")
this.products = this.http.get('/api/products',{headers:myHeaders})
.map((res)=> res.json());
}