Angular 4200端口显示带有html的数据,而nodejs 8080端口显示不带html的json数据 [英] Angular 4200 port showing data with html but nodejs 8080 port showing json data without html

查看:99
本文介绍了Angular 4200端口显示带有html的数据,而nodejs 8080端口显示不带html的json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有结点js的angular 5来制作事件数据. 当我尝试从通过Angle运行的4200 port (http://localhost:4200/event)获取事件数据时,工作正常.它以html格式显示所有值.但是,当我使用来自nodejs的8080 port (http://localhost:8080/event)时,它仅在json中显示数据.这里没有显示来自event.component.html的html内容. express.js看起来像这样

I am using angular 5 with node js to make a crud for events data. When I am trying to get events data from 4200 port(http://localhost:4200/event) which is running through angular is working well. It is showing the data in html with all the values. But when I am using 8080 port(http://localhost:8080/event) which one is from nodejs it is showing data only in json. No html content from event.component.html is showing here. express.js looks like this

/* ===================
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看起来像这样

my event.router.js looks like this

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看起来像这样

event.component.html looks like this

<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看起来像这样

event.components.ts looks like this

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看起来像这样

event.service.ts looks like this

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获取数据?任何帮助和建议都将非常可观.

So can someone tell me what is the wrong here. Why I am getting data as json in 8080 port and why its showing fine with 4200 port? How I will get the data with html in 8080 port? Any help and suggestions will be really appreciable.

推荐答案

我知道当我告诉您将事件移至其他答案中的get *请求上方时,就会发生这种冲突.

I knew this collision would occur when I told you to move events above get * request in other answer.

这就是为什么建议使用/api路由的原因.

That is why suggested the /api route.

这里发生的事情是:-

从节点提供角度应用程序时.即在端口8080上并请求

When you are serving your angular app from node. i.e on port 8080 and request

http://localhost:8080/events

express在事件模块中找到了该路由,因此它以JSON形式返回数据,并且请求不会转到您返回索引文件的路由(需要加载角度)

the express finds this route registered in events module, so it returns the data, which is in form of JSON and the request does not go to the route where you return the index file (needed to load angular)

当localhost:4200请求直接发送到有角度的CLI时,它们不会与快速路径冲突.

While localhost:4200 request are directly sent to angular CLI so they don't collide with express path.

正如我建议的那样,只需将"/api"路径放在您在express中制作的每个api之前,您的问题将得到解决,因为express将不再具有"/events"路径,因此它将请求传递给应用.get(*)函数和您的角度文件将被提供.

As I suggested, Just put the "/api" path ahead of every api that you make in express and your issue would be resolved as express will no longer have an "/events" path so it will pass the request to app.get(*) function and your angular file would be served.

注意/api只是一个标准的命名约定,您可以放入xyz,它也可以正常工作.

NOTE /api is just a standard naming convention, You can put xyz and it would work as well.

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

This practice will also ensure that You don't face the same problem in other requests.

这篇关于Angular 4200端口显示带有html的数据,而nodejs 8080端口显示不带html的json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆