在使用angular2中使用nodejs创建服务器,并成功获取参数

本文通过实战演示如何使用Node.js的Express框架搭建服务器,并通过Angular实现前后端交互,包括安装配置、数据获取及解决跨域问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

老是遇到很多坑等着自己去填.

首先创建服务器:

1.最好使用express,这个库有更多的api,方法:npm install express --save;

2. npm install @types/express --save;

安装nodemon 可以让服务器自动重启,

方法:npm install nodemon;

在启动服务器的时候用:nodemon build/...js;

这样服务器就算启动完成了.

/**
 * Created by Administrator on 2017/5/16.
 */
import * as express from "express";
const app=express();

app.get("/", (req,res)=>{
  res.send("hello express")
})
export class Produce{
  constructor(
    public id:number,
    public title:string,
    public price:number,
    public rating:number,
    public desc:string,
    public categories:Array<any>
  ){

  }
}

const products:Produce[] =[
  new Produce(1,"第一个商品",1.99,3.5,"这是第一个商品描述",["图书","音乐"]),
  new Produce(2,"第二个商品",3.99,2.5,"这是第二个商品描述",["语文"]),
  new Produce(3,"第三个商品",4.99,4.5,"这是第三个商品描述",["音乐","体育"]),
  new Produce(4,"第四个商品",5.99,1.5,"这是第四个商品描述",["化学","体育"]),
  new Produce(5,"第五个商品",16.99,4.5,"这是第五个商品描述",["生物","图书"]),
  new Produce(6,"第六个商品",12.99,3.5,"这是第六个商品描述",["科学"]),
]



app.get("/api/products",(req,res)=>{
  res.json(products)
})
app.get("/api/products/:id",(req,res)=>{
  //在命令行中打印,当发送个请求的时候才触发,
  // console.log(req.params)
  res.json(products.find( produce => produce.id==req.params.id))
})

const server =app.listen(8000,"localhost",()=>{
  console.log("服务器已经启动,地址是http://localhost:8000")
});

接着在本地从创建好的服务器上获取数据:

import { Component, OnInit } from '@angular/core';
import {Observable} from "rxjs";
import {Http} from "@angular/http";
import "rxjs/Rx"


@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
  dataSource:Observable<any>;

  products :Array<any>=[];

  constructor(private http:Http) {
    console.log(http)
    this.dataSource = this.http.get('/api/products')
      .map((res)=>res.json())
    console.log(this.dataSource)
  }

  ngOnInit() {
    this.dataSource.subscribe((data)=>{
      this.products=data
    })
  }

}

dataSource:Observable<any> 将获得的数据保存为流.对应 的需要引入Observable from "rxjs"

http服务已经在app.module中引入过了,这里需要声明在构造函数里头,并引入Http from "@angular/Http";

 

接着就是坑了,写完后,发现还是获取不到服务器上的数据:

接下来还有配置:

在根目录新建一个文件:proxy.conf.json  内容为:

{
  "/api":{
    "target":"http://localhost:8000"
  }
}

 

然后在package.json文件中,修改一行

"start": "ng serve --proxy-config proxy.confi.json",

然后启动

要用npm run start;

只要使用这个命令,才能告诉页面,需要到这个地址去拿数据.

 

转载于:https://my.oschina.net/kaykie/blog/902253

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值