3

I would like to replace the built in server in angular-cli with express, so that I can edit the express javascript to add widgets I need executing on the server. How can that be done?

user3567174
  • 1,898
  • 2
  • 15
  • 18
  • I've heard that angular-cli uses a lot from ember-cli. So searching for 'ember-cli replace server with express', found [this](http://stackoverflow.com/questions/24336040/how-to-use-a-custom-express-server-with-ember-cli). However angular-cli doesn't implement `api-stub`. – user3567174 Jul 01 '16 at 20:03
  • Did you find a solution for this? – eko Apr 27 '17 at 05:40

2 Answers2

1

I added an app.js file to the src folder generated by the angular-cli, and wrote a simple server. When you run ng build, the files you add to the src and public directories will be complied and added to the dist directory. So you should render/send relative to the index.html file in dist:

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

To run the express server from the terminal: $ node dist/app.js

I get some compiler errors when I try to nest the app.js file: src/server/app.js, but all the other server files work fine when nested, such as models and routes.

Chris
  • 161
  • 1
  • 10
0

The best solution is to replace it with one the Ember CLI expects (and is thusly implemented in the Angular CLI packages). I use mine to proxy b/c I never got the -proxy option to work correctly.

First, ensure you have express installed:

$ npm install express --save-dev

Create an express server specifically at /server/index.js

./server/index.js ->

var express = require('express');
module.exports = express();

That's as simple as it gets. The 'ng serve' handles serving static files, so there's no need to add your own. If you want to add something to it like your reverse proxies, just construct and add it to the app before exporting:

var express = require('express');
var httpProxy = require('http-proxy');
var app = express();
app.all('/api/*', function(req, res) {
  var proxy = httpProxy.createServer('http://localhost:8000');
  req.url = req.url.replace(/^\/api/i, '');
  proxy.web(req, res);
});
module.exports = app;

Note that Ember CLI does support proxies, though I haven't had much luck using it for what I need.

Steve Hynding
  • 1,799
  • 1
  • 12
  • 22