简体   繁体   中英

How do I serve an Angular application from existing nodejs server?

I have an Angular 6 application and an existing nodejs api application. So far I have used

ng serve

to run and build the angular application.

I now want to serve my angular application from the existing node js server.

How do I do that ? I can't find any documentation.

Steps:

  1. Do ng build , It will create a dist folder which you can easily serve from node webserver framework like express , Hapi or Koa
  2. if you are using express.js you can server angular app.use(express.static(path.join(__dirname, 'dist'))) ;
  3. Now use node server URL to serve angular like http://localhost:nodeport

If you are using Hapi: check this out https://hapi.dev/tutorials/servingfiles/?lang=en_US

================================basic express server================

const express = require('express');
const app = express();
const path = require("path");
const fs = require("fs");




//const bodyParser = require('body-parser');
app.use(express.static(path.join(__dirname, 'dist')));
//app.use(bodyParser.json());


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

 app.listen(8080,function(err){
   if(!err){
    console.log("server is running at port:8080);
   }
 })

You have two ways of serving an Angular SPA:

  • Usually dev : the Webpack-run server, which is ng serve . Dynamic in the sense that any modification to a file starts a rebuild and updates the output.

  • Usually prod : you build all the html/js files (with ng build [...] ) for the SPA to be statically served by a node server.

In your case, if you'd like to use an existing node server, it means you'll have to build the files (with ng build ) and then hook up the usual node static files serving snippet in your node app.

Beware though: you'll have to do a full build each time you want to update the display. So it's ok if it's not that often, but not ok for a dev environment I guess.

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