简体   繁体   中英

MEAN app. Two servers at the same time Express, NodeJS, Angular 2

I try to connect backend (NodeJS, Express) with Frontend (Angular 2), but have a problem.

When I start two servers separately, both client-side and server-side work fine. In my situation: localhost:4200 - Angular localhost:3000 - NodeJS, Express

When I render any static html file in my VIEWS folder, it works correctly, but when I change the content of the html file to Angular Index.html, that uses components, it doesn't work. I mean, it works, but doesn't load my components.

I suppose that problem is in the configuration, and my index.html doesn't know how to find and load components, but I don't understand exactly where a mistake might be.

When I try to start both servers at the same port, my frontend part stops working.

I use Angular-CLI, NodeJS, Express and EJS.

My server.js code is:

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

var index = require('./routes/index');
var tasks = require('./routes/tasks');

var port = 3000;

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view enjine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'views')));

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

app.use('/', index);
app.use('/api', tasks);

app.listen(port, function () {
    console.log('Server started on port ' + port);
});

In the ROUTES folder my index.js code is:

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

router.get('/', function(req, res, next) {
    res.render('index.html');
});

module.exports = router;

My folders structure: Picture of foldes

 node_modules
 routes
 ruen-app
 views
package.json
server.js 

ruen-app is my client (Angular 2) folder.

So, my questions are:

  1. How to connect these two parts?
  2. Is it correct to start two servers at the same time - one for the frontend, another for the backend?
  3. What is the best practice for MEAN applications to start from the scratch? I mean, what is the best way - two servers or one?

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