Angular 2 cli with Express js

2020-07-12 05:54发布

问题:

I want to use express js w/ node js to be my server for an angular 2 project. I was looking at tutorials for integrating express js w/ the angular cli (I followed this and this) and I had no luck. Does anyone have any suggestions on how to do this? Currently I have a new project up w/ cli just something that says "app works!" and want to try to do it using express as opposed to using the lite server.

any help is appreciated!

回答1:

this link works for me, but with some changes.

I install angular-cli and create new project, then I follow the tutorial of the link but with this changes:

  1. I create a folder called node_server
  2. In run npm install express --save in root folder of my project. This add server like dependencie in your package.json without create new on node_server.
  3. I create a new file in node_server called server.js, with a basic express server. This server only returns the index.html of dist folder.
  4. Added the scripts to the package.json, the scripts are the same in the link tutorial, but with one change, the filename is server.js not index.js

This is my server.js file :

const express = require('express');

var app = express();  
var staticRoot = __dirname;  

app.set('port', (process.env.PORT || 3000));  

app.use(express.static(staticRoot));

app.get('/', function(req, res) {
    res.sendFile('index.html');
});

app.listen(app.get('port'), function() {  
    console.log('app running on port', app.get('port'));
});

I hope this works for you.



回答2:

The above comment worked pretty well for me, just needed to make some adjustments to the scripts in package.json suggested in that link.

"build:nodeserver": "ng build && cp node-server/* dist",

"build:nodeserver-prod": "ng build -prod && cp node-server/* dist",

"serve-build" : "npm run build:nodeserver && nodemon dist/index.js",

"serve-build-prod": "npm run build:nodeserver-prod && nodemon dist/index.js"

I have a folder called node-server which has my server.js file like above with routes for angular2 app as above, and some api routes in there too, and some other folders in the node-server like mysql-requests and some files like config.json file



回答3:

What I do create 2 folder on is your express server (I am using Express-generator) and 1 is Angular 2 project (Angular cli )

root folder

--->server

--->ng4

---> gulpfile.js

gulp will build your app and move build files

var gulp = require('gulp')
var rename = require("gulp-rename");
var deletefile = require('gulp-delete-file');
var exec = require('child_process').exec;
var runSequence = require('run-sequence');

gulp.task('build', function (cb) {
  exec('cd ng4/ && ng build', function (err, stdout, stderr) {
    cb(err);
  });
})

gulp.task('rename', () => {
    return gulp.src("./ng4/dist/index.html")        
        .pipe(rename("ng4.html"))
        .pipe(gulp.dest("./server/views"));
})

gulp.task('deletefile', function () {
    var regexp = /\w*(\-\w{8}\.js){1}$|\w*(\-\w{8}\.html){1}$/;
    gulp.src(['./server/public/index.html',
            './ng4/dist/**/*.*'])
    .pipe(deletefile({reg: regexp,deleteMatch: false}));
});

gulp.task('move', function () {
    return gulp.src(["./ng4/dist/**/*.*"])       
        .pipe(gulp.dest("./server/public"));
});

gulp.task('default', function(callback) {
    runSequence('build','rename','move','deletefile',callback)    
});

In this way you can developed in ng4 app and run gulp command on root .



回答4:

I have this scenario; however, I want to be able to:

  1. run my angular CLI project using ng serve instead of modifying any gulp tasks/ processes and without having to run ng build every time
  2. have a server-side API responding on its own port independently of the frontend -- this way the microservice architecture pattern is used and concerns between frontend and backend are separated.

To accomplish this, I used concurrently with the below package.json script modifications

  "scripts": {
    "start": "concurrently \"npm run-script start-frontend\" \"npm run-script start-backend\"",
    "start-frontend": "ng serve",
    "start-backend": "node index.js",
    ...

My backend index.js file is boilerplate but looks like this...

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

const app = express();
const PORT = process.env.PORT || 3000;

router.get('/', (req, res) => {
    res.json({ Hello: 'World' });
});

app.use('/api', router);
app.listen(PORT, function() {
    console.log(`API running on port ${PORT}`);
});

Now, when I want to run the app, I can type npm start to get everything running. Then, I can go to...

  • http://localhost:3000/api/ to access the backend
  • http://localhost:4200/ to access the frontend