How to serve an angular2 app in a node.js server

前端 未结 5 497
你的背包
你的背包 2021-01-01 23:41

I\'m building a web app using Angular2, to create the project I\'m using Angular2 CLI webpack. Angular2 app uses other external packages also (Eg: Firebase). In addition to

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-02 00:02

    1. Use ng build to build your app into build directory.
    2. Create nodejs app to server the build directory as static content, then create route for api.

    Following is an example of nodejs app using express that will serve the Angular2 app:

    /*
    Put content of angular2 build into 'public' folder.
    */
    const html = __dirname + '/public';
    
    const port = 4000;
    const apiUrl = '/api';
    
    // Express
    const bodyParser = require('body-parser');
    const compression = require('compression');
    const express = require('express');
    var app = express();
    
    app
        .use(compression())
        .use(bodyParser.json())
        // Static content
        .use(express.static(html))
        // Default route
        .use(function(req, res) {
          res.sendFile(html + 'index.html');
        })
        // Start server
        .listen(port, function () {
            console.log('Port: ' + port);
            console.log('Html: ' + html);
        });
    
    // continue with api code below ...
    

提交回复
热议问题