Search code examples
node.jsangulartypescriptexpressmean-stack

MEAN: nodejs server for Angular App - How do i serve angular routes


Here is my node server.js it is in the project root with its own npm config. All Angular files are in /client hence after ng build the dist will be at client/dist

enter image description here

const express = require('express');
const colors = require('colors');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');

const PORT = process.env.port||'3200';

// init "app"
const app = express();

app.use(cors({origin: `http://localhost:4200`}));

// angular entry point
app.use(express.static(path.join(__dirname, 'client/dist')));

//parse incoming data before routes
app.use(bodyParser.json())

// api routes
app.use('/api',require('./api/api'));

// error middleware
app.use(function(err, req, res, next){
    console.log(`${err}`.red.bold)
    res.status(422).send({error: err.message });
});

// listen
app.listen(PORT, function(){
    console.log(`app running on ${PORT}...`.magenta);
});

When I go to the server http://localhost:3200/ I see my angular app. and when I go to http://localhost:3200/api/someExpressRoute I get my api functions. great

Now I need to figure out how to serve angular routes. for example http://localhost:3200/about is part of my angular single page app. But when I go to that url the server doesnt know what to do.

How do I configure this server to handle http://localhost:3200/* as an angular route that is served from index?


Solution

  • Here's how I serve my angular application via nodejs:

    var express = require('express'),
       path = require('path'),
       fs = require('fs');
    var compression = require('compression');
    var app = express();
    var staticRoot = __dirname + '/';
    var env = process.env.NODE_ENV || 'development';
    
    app.set('port', (process.env.PORT || 5000));
    
    app.use(compression());
    /* other middleware */
    
    /* place any backend routes you have here */    
    
    app.use(function(req, res, next) {
        //if the request is not html then move along
        var accept = req.accepts('html', 'json', 'xml');
        if (accept !== 'html') {
            return next();
        }
    
        // if the request has a '.' assume that it's for a file, move along
        var ext = path.extname(req.path);
        if (ext !== '') {
            return next();
        }
    
        fs.createReadStream(staticRoot + 'index.html').pipe(res);
    
    });
    
    app.use(express.static(staticRoot));
    
    app.listen(app.get('port'), function() {
        console.log('app running on port', app.get('port'));
    });
    

    When serving the application, ensure all of your frontend dist files are in the same folder as this file (which I call index.js)