Angular 4200端口显示数据与html但nodejs 8080端口显示json数据没有html

时间:2018-02-06 07:53:16

标签: javascript json node.js angular

我正在使用带有节点js的angular 5来为事件数据制作一个crud。 当我试图从通过角度运行的4200端口(http://localhost:4200/event)获取事件数据时运行良好。它以html显示所有值的数据。但是当我使用8080端口(http://localhost:8080/event)时,其中一个来自nodejs,它只在json中显示数据。此处未显示event.component.html中的html内容。 express.js看起来像这样

/* ===================
Import Node Modules
=================== */
const express = require('express');
const app = express();
const router = express.Router();

const mongoose = require('mongoose');
const config = require('./database');
const path = require('path');
const appRoot = require('app-root-path');

//custom module
const event = require('../config/routes/event.router');

const bodyParser = require('body-parser');
const cors = require('cors');
const port = process.env.PORT || 8080; // Allows heroku to set port


mongoose.Promise = global.Promise;
//assigning value 
process.env.NODE_ENV = 'devlopment';

/**
 * Database connection
 */

mongoose.connect(config.uri, {
  useMongoClient: true,
}, (err) => {
  // Check if database was able to connect
  if (err) {
    console.log('Could NOT connect to database: ', err); // Return error message
  } else {
    console.log('Connected to ' + config.db); // Return success message
  }
});

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


app.use(express.static(path.join(appRoot.path, 'dist')));

/**
 * Routing
 */

app.use('/event', event); //Event Router

app.get('*', (req, res) => {
 res.sendFile(path.join(appRoot.path, 'dist/index.html'));
});

/**
 * Assiging port to server
 */
app.listen(port, () => {
  console.log('Listening on port ' + port + ' in ' + process.env.NODE_ENV + ' mode');
});

我的event.router.js看起来像这样

const Event = require('../../model/event.model');
var multer  = require('multer');
var upload  = multer({ dest: './public/uploads/img/',fileFilter:function(req,file,cb){
  var ext = file.originalname.split('.').pop();
  cb(null, file.fieldname + '-' + Date.now() + '.' + ext);
    }
}).single('eventimage');

/* GET ALL EVENTS */
router.get('/', function(req, res, next) {
  Event.find(function (err, events) {
    if (err) return next(err);
    res.json(events);
  });
});

/* GET SINGLE EVENT BY ID */
 router.get('/:id', function(req, res, next) {
   Event.findById(req.params.id, function (err, post) {
     if (err) return next(err);
     res.json(post);
   });
 });

module.exports = router;

event.component.html看起来像这样

<div class="container">
  <h1>Event List</h1>
  <table class="table">
    <thead>
      <tr>
        <th>Event Id</th>
        <th>Event Name</th>
        <th>Event Desc</th>
        <th>Event Date</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let event of events">
        <td><a routerLink="/event-details/{{ event._id }}">{{ event._id }}</a></td>
        <td>{{ event.eventname }}</td>
        <td>{{ event.eventdesc }}</td>
        <td>{{ event.eventdates }}</td>
      </tr>
    </tbody>
  </table>
</div>

event.components.ts看起来像这样

import { Component, OnInit } from '@angular/core';
import { EventService } from '../event.service';

@Component({
  selector: 'app-event',
  templateUrl: './event.component.html',
  styleUrls: ['./event.component.css']
})
export class EventComponent implements OnInit {

  events: Event[] = [];

  constructor(
    protected eventService: EventService
    ) { }

  ngOnInit() {
    this.getAll();
  }

  getAll() {
    this.eventService.getEvents().subscribe(res => {
      this.events = res as Event[];
    }, err => {
      console.log(err);
    });
  }
}

event.service.ts看起来像这样

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import { HttpClientModule } from '@angular/common/http';

import { HttpClient } from "@angular/common/http";
import 'rxjs/add/operator/map';


@Injectable()
export class EventService {

  domain = 'http://localhost:8080';

  headers = new Headers({ 'Content-Type': 'application/json' });

  constructor(
   private http: Http,
    ) { }

  getEvent(id: string) {
    return this.http.get(this.domain + '/event/' + id, { headers: this.headers }).map(res => res.json());
  }

  getEvents(){
    return this.http.get( this.domain + '/event', {headers: this.headers}).map(res => res.json() );
  }

}

所以有人可以告诉我这里有什么不对。为什么我在8080端口获取数据为json以及为什么它在4200端口显示正常?我将如何使用8080端口的html获取数据?任何帮助和建议都会非常明显。

3 个答案:

答案 0 :(得分:1)

您的事件路由是在角度应用中为事件调用提供json,而不是呈现它。

您的角度应用程序也在4200上的Web服务器上运行,这可能是某种开发服务器。然后,请求被代理到提供后端数据的快速服务器。

要使用快速应用程序来渲染角色应用程序,您需要构建应用程序并将文件放入快速应用程序的dist文件夹中。然后,任何路径其他而不是/ event将呈现角度应用。这是显示该部分的代码部分。

app.get('*', (req, res) => {
 res.sendFile(path.join(appRoot.path, 'dist/index.html'));
});

如果您处于开发环境中,则无需担心这一点。您可以访问端口4200上的角度应用程序和8080上的快速应用程序

答案 1 :(得分:1)

我知道当我告诉你在其他答案中将事件移到get * request之上时会发生这种碰撞。

这就是为什么建议/ api路线。

这里发生的事情是: -

当您从节点提供角度应用程序时。即在端口8080和请求

http://localhost:8080/events

express发现此路由在事件模块中注册,因此它返回数据,该数据采用JSON格式,请求不会返回返回索引文件的路径(需要加载角度)

localhost:4200请求直接发送到角度CLI,因此它们不会与快速路径冲突。

正如我所说,只需把#34; / api&#34;你在快递中制作的每一个api之前的路径,你的问题将得到解决,因为快递将不再有&#34; / events&#34;路径,所以它会将请求传递给app.get(*)函数,你的角度文件将被提供。

注意 / api只是一个标准的命名约定,你可以放xyz,它也可以。

这种做法还可以确保您在其他请求中不会遇到同样的问题。

答案 2 :(得分:0)

使用端口4200中的数据查看HTML是非常合乎逻辑的,因为在此端口中您托管Angular的HTML文件,因此无论您的后端是否工作,您都将看到HTML。

在端口8080上这也是非常合乎逻辑的,因为托管后端的端口只发送数据,而这个端口是端口4200上提供数据的HTML端口。