简体   繁体   English

使用dist文件夹时,Angular 5无法从NodeJs,Mongodb获取数据

[英]Angular 5 not getting the data from NodeJs, Mongodb when dist folder has been used

I am using angular 5 with node js for creating and getting events data. 我正在使用带有节点js的angular 5来创建和获取事件数据。 I have my express.js file looks like this 我的express.js文件如下所示

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');

const event = require('./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';

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')));
app.get('*', (req, res) => {
 res.sendFile(path.join(appRoot.path, 'dist/index.html'));
});

app.use('/event', event); //Event Router
app.listen(port, () => {
  console.log('Listening on port ' + port + ' in ' + process.env.NODE_ENV + ' mode');
});

event.router.js looks like this event.router.js看起来像这样

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');

const Event = require('../../model/event.model');

/* GET ALL EVENTS FROM DB */
router.get('/', function(req, res, next) {
  console.log(Event);
  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;

my event.component.html looks like this 我的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.component.ts looks like this event.component.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[];
      console.log(res);
    }, err => {
      console.log(err);
    });
  }
}

event.service.ts looks like this 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 {


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

  constructor(
   private http: Http,
    ) { }




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

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

}

The problem is when I am trying to fetch all the data from the mongodb it is showing error like GET http://localhost:8080/event 404 (Not Found) in the console tab of the browser. 问题是,当我尝试从mongodb中获取所有数据时,它在浏览器的控制台选项卡中显示了类似GET http://localhost:8080/event 404 (Not Found) But when I am deleting the line 但是当我删除行时

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

from express.js it is showing the data. 从express.js显示数据。 But I think that line should be in the express.js file because when the angular will build the data it should get all the html and component from that folder. 但是我认为该行应该在express.js文件中,因为当angular创建数据时,它应该从该文件夹中获取所有html和组件。 So can someone tell me where I am doing wrong? 有人可以告诉我我做错了什么吗?

Any help and suggestions will be really appreciable. 任何帮助和建议都是非常可取的。

Put your 把你的

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

After

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

Reason behind this is, Express is returning index file on every get request without checking with other routes as you have the * route before event, As you change the position, Express will find event route first, so on event url will use the event controller and for other URL, It will return index.html 这背后的原因是,Express在每个获取请求上都返回索引文件,而不检查其他路由,因为您在事件之前具有*路由,随着位置的更改,Express将首先查找事件路由,因此事件url将使用事件控制器对于其他URL,它将返回index.html

Also, Keep a practice of keeping your every API after "api/" route, like for get event api route would be /api/events 另外,请保持在“ api /”路由之后保留每个API的做法,例如,获取事件api路由应为/ api / events

This will seperate your api code with angular routes. 这将用角路由分隔您的api代码。

Imagine you have a /events route in your angular app. 想象一下,您的角度应用程序中有一个/ events路由。 So if you type http://localhost/events route in your url bar, You will get response of your list of events mongoDB api, rather than the page you wanted. 因此,如果您在网址栏中输入http:// localhost / events route,则会得到事件列表mongoDB api的响应,而不是所需的页面。

EDIT Links for more understanding of the same. 编辑链接以获得更多的了解。

https://malcoded.com/posts/angular-backend-express https://malcoded.com/posts/angular-backend-express

https://www.reddit.com/r/angularjs/comments/2f4858/angular_express_best_way_to_handle_routing/ https://www.reddit.com/r/angularjs/comments/2f4858/angular_express_best_way_to_handle_routing/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM