通过不带Express的Node与Angular6一起使用模拟API

时间:2018-10-09 14:50:06

标签: node.js angular rest

到目前为止,我已经能够使用Angular的HttpClient模块本身使用模拟API。我现在正在尝试构建后端以通过Node.js提供API。这是因为稍后我要提供应用程序的真实数据并将其保存在数据库中。

但是我在弄清楚如何使用 Node的 http模块时遇到了麻烦。我意识到Express可以包装很多样板,但是我喜欢在学习时尽量保持原始状态。稍后我将学习Express。

mock API从网站嘲笑API提供JSON字符串。如前所述,如果直接调用模拟,前端REST api可以获取数据。但是现在,我对Node的Http.ClientRequest和Http.ServerResponse对象产生了误解。

所以从后到前:

后端脚本(节点): app.js

const request = require('request');
const http = require('http');

//returns a stream
let s = request('https://5b82c6892fd7f2001417916a.mockapi.io/mock');

let data = ''

s.on('data', (chunk) => {
data += chunk;
});

JSON.stringify(data);

s.on('end', () => {
console.log('Got data');
});

server = http.createServer((req, res) => {

const headers = { 
    'Content-Type': 'application/json',     
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
    'Access-Control-Max-Age': 2592000, // 30 days
};

    res.writeHead(204, headers);    
    res.write(data);
    res.end();
});

server.listen(3500);

前端REST API(Angular6):data.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs'

//
import { Transaction } from '../models/transaction.model';


@Injectable({
  providedIn: 'root'
})



export class DataService {
  //https://5b82c6892fd7f2001417916a.mockapi.io/mock
  //
  baseUrl: string = 'http://localhost:3500/';

  constructor(private http: HttpClient) { }

  getAllTransactions(): Observable<Transaction[]> {
    return this.http.get<Transaction[]>(this.baseUrl);

  }

}

调用REST API(ng6)的Repo服务:transaction-respository.service.ts

import { Injectable } from '@angular/core';

//
import { DataService } from './data.service';
import { Transaction } from '../models/transaction.model';

@Injectable({
  providedIn: 'root'
})
export class TransactionRepositoryService {

  private transactions: Transaction[];

  constructor(private dataservice: DataService) {
    this.dataservice.getAllTransactions().subscribe(
      (data) => { this.transactions = data; console.log('Transactions Received') },
      (error) => console.log(error),
      () => console.log('Repo GET request ended'));
  }

  getAllTransactions(): Transaction[]{
    return this.transactions;
  }

}

调用回购服务(ng6)的nG组件:transactions.component.ts

import { Component, OnInit } from '@angular/core';
import { Transaction } from '../../models/transaction.model';
import { TransactionRepositoryService } from '../../services/transaction-repository.service';

@Component({
  selector: 'app-transactions',
  templateUrl: './transactions.component.html',
  styleUrls: ['./transactions.component.css']
})

export class TransactionsComponent implements OnInit {

  private transactions: Transaction[];
  private sortParam: number = 0;


  constructor(private repo: TransactionRepositoryService) {
    this.transactions = this.repo.getAllTransactions();
  }

  ngOnInit() {

  }

  get trans(): Transaction[] {
    return this.transactions;
  }


}

该组件的模板(ng6):transactions.component.html

<table>
  <thead>
    <tr>
      <td>ID</td>
      <td>Date/Time</td>
      <td>Vendor</td>
      <td>Category</td>
      <td>Amount</td>
      <td>Options</td>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let t of trans">
      <td>
        {{t.id}}
      </td>
      <td>
        {{t.date}}
      </td>
      <td>
        {{t.vendor}}
      </td>
      <td>
        <input type="text" placeholder="category here" />
      </td>
      <td>
        {{t.amt}}
      </td>
      <td>

      </td>
    </tr>
  </tbody>
</table>

所涉及的数据模型(ng6):transaction.model.ts

export class Transaction{
  constructor(
    public id: number,
    public date: Date,
    public vendor: string,
    public amt: number,
    public category?: string
  ){}


}

非常感谢

1 个答案:

答案 0 :(得分:0)

res.writeHead(204, headers)更改为res.writeHead(200,header);