简体   繁体   中英

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. I have my express.js file looks like this

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

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

<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

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

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. 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. 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. 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

Also, Keep a practice of keeping your every API after "api/" route, like for get event api route would be /api/events

This will seperate your api code with angular routes.

Imagine you have a /events route in your angular app. 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.

EDIT Links for more understanding of the same.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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