Tuesday, 2 May 2017

Can't render Index.html file in MEAN app

I'm having trouble setting up the routes between nodejs and angularjs in my MEAN app. I've tried adding a view engine but don't know if I truly need one and keep getting stuck with either a 'Cannt get /route' error or a no engine error. Can someone help me with my app setup? Sorry, I'm relatively new to nodejs.

Here is my server.js file

const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require("body-parser");
const mongoose = require('mongoose');

const appRoutes = require('./routes/app');
const keyRoutes = require('./routes/keys');
const mailRoutes = require('./routes/mail');

const app = express();
const uristring =
  process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/db';

mongoose.connect(uristring, function (err, res) {
  if (err) {
    console.log ('ERROR connecting to: ' + uristring + '. ' + err);
  } else {
    console.log ('Succeeded connecting to: ' + uristring);
  }
  });

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());

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


app.use(function (req,res,next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
  next();

});

app.use('/event', appRoutes);
app.use('/mail', mailRoutes);
app.use('/keys', keyRoutes);
app.use('/', appRoutes);

//catch 404 and forward error handler
app.get('*', function(req,res) {
  res.sendFile(__dirname, 'dist/index.html');
});

app.listen(process.env.PORT || 8080);

module.exports = app;

Here is the app routes file

const express = require('express');
const router = express.Router();

router.get('/', function (req, res, next) {
  res.render('dist/index');
});

router.get('/event', function(req, res, next) {
  res.render('dist/index');
});

module.exports = router;

Here is the basics of my file tree

appName
-dist
-e2e
-node_modules
-routes
--app.js

-src
--app
---app.module.ts (my angular routes)

--assets

-server.js
-all other files

Also, here are my paths in my angular module

const appRoutes: Routes = [
  { path: '', component: HeaderComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'event', component: EventComponent },
  { path: 'gallery', component: GalleryComponent },
  { path: 'thankyou', component: ThankyouPageModalComponent }
];

All I want is when someone searches app/event they will be routed correctly. Thanks for any help!



via Jonathan Corrin

No comments:

Post a Comment