Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How run in same port Angular and Node.JS Express?

This is might be possible to duplicate question but not able to understand how to configure FE and BE together run them both.

I've gone through this and this questions, but couldn't understand.

My Node+Express running on 4300

app.post('/postData', function(req, res) {
//some worst logics here :)
});

And

Angular 5 running on 4200. Below is my FE service that calling post endpoint

postData(feData) {
        console.log(feData);
        this.http.post('/postData', feData, this.httpHeader).subscribe((data) => {
        });
    }

What I tried is opened two cmd Windows: one to run server.js by node server.js and another one with ng serve.

Result:

404 not fount(cannot post)

What am I doing wrong.

like image 410
Mr. Learner Avatar asked Jun 18 '18 13:06

Mr. Learner


2 Answers

What you need to do on this case is move your Angular 5 application to run under express process. You can achieve this following this tutorial - See item 2

I removed some complications but I really recommend you to take a look on the tutorial.

npm install --save express body-parser

Create a file to run your node app like server.js and add following code:

var app = require('app.js');
var debug = require('debug')('mean-app:server');
var http = require('http');

var port = normalizePort(process.env.PORT || '4300');
app.set('port', port);

var server = http.createServer(app);
server.listen(port);
server.on('listening', onListening);

function onListening() {
  var addr = server.address();
  debug('Listening on ' + port);
}

Edit "package.json" to specify how you app will start:

"scripts": {
  "ng": "ng",
  "start": "ng build && node server.js",
  "build": "ng build",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},

Now, create app.js which will run express:

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var sample = require('./routes/sample.js');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'false'}));

//Put your angular dist folder here
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/samples', express.static(path.join(__dirname, 'dist')));
app.use('/sample', sample);

module.exports = app;

It's a good practice to create routes folder for your elements. Create a file routes/sample.js with following content:

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

router.get('/', function(req, res, next) {
  res.send('RESTful API');
});

module.exports = router;

Run the server using node command:

npm start
like image 191
Marcio Jasinski Avatar answered Sep 20 '22 19:09

Marcio Jasinski


By Experience, Keep the Backend or Microservices separate from your frontend applications.

like image 21
Joel Wembo Avatar answered Sep 21 '22 19:09

Joel Wembo