首页 > 解决方案 > 通过 Node w/o Express 使用 Angular6 使用 mockAPI

问题描述

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

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

模拟 API 提供来自网站 mockapi.io 的 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;
  }

}

调用 repo 服务的 nG 组件 (ng6) :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
  ){}


}

非常感激,

标签: node.jsangularrest

解决方案


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


推荐阅读