How to do it...

This section covers how to implement static file serving in Express.

  1. First, let's build our Angular application by running the Angular-CLI build command in our project directory:
ng build
  1. Next, let's create a new /routes/angular.js route in our Express project, to configure serving our Angular application. We will need to define a relative route from this project to our Angular project using Node.js's core path module:
var path = require('path');
var express = require('express');
var router = express.Router();
var angularBuildPath = path.resolve(__dirname,
'../../my-angular-project/dist');

router.use(express.static(angularBuildPath));

router.get('*', (req, res, next) => {
if (req.url.startsWith('/api')) return next();
res.sendFile(path.join(angularBuildPath,
'index.html'));
});

module.exports = router;
  1. We will have to update our /app.js Express configuration to load our new route configuration. Since it will serve most of the content for our application, we will place it before our API configuration. We'll also remove the index and user routes that were generated when we originally created the project with express-generator:
...
var api = require('./routes/api');
var angular = require('./routes/angular');
...
app.use('/', angular);
app.use('/api', api);
...
  1. Finally, we no longer need to render views from our Express app, so we should update our error handler in /app.js so that it will instead serve JSON error messages to us when there is an unresolved request:
...
app.use('/', angular);
app.use('/api', api);
app.use(function(req, res) {
var error = new Error('Not Found');
res.status(404).json({
status: 404,
message: error.message,
name: error.name
});
});

module.exports = app;
  1. Restart your Express server and navigate to localhost:3000/. You will see your Angular application load. Navigating to localhost:3000/api/ will still serve the API status page.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.43.134