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

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:
How to connect these two parts?
Is it correct to start two servers at the same time - one for the frontend, another for the backend?
What is the best practice for MEAN applications to start from the scratch? I mean, what is the best way - two servers or one?

Spent 3 days, but found the solution.
On the stackoverflow:
Different ports for frontend and backend. How to make a request?
Angular-CLI proxy to backend doesn't work

Related

Can I use home.ejs instead of index.html?

The problem is, that when I'm deploying my website with FileZilla, I get a 403 forbidden. After a bit of searching for answers, it seems like it's because I don't have an index.html, but I'm using home.ejs instead. Can I set up my project, so it uses the home.ejs instead of an index.html?
I've made a one page website (which is going to be expanded to more pages), that works as a resume and I now need to deploy it to my domain.
It is the 2nd version of my website, as I've been making it alongside a web development course I've been taking. The first version was made from html, css and Bootstrap, as a static page. The new version includes JavaScript, node.js, express and ejs.
My file structure looks like this
Project:
node_modules
public
css
images
views:
partials
header.ejs
footer.ejs
home.ejs
app.js
package-lock.json
package.json
Everything works when I deploy it locally (localhost:3000). I am pretty new to the whole web development thing. Even though the course I took was really good, it didn't talk about deploying a website to your own domain name.
Here is the app.js file:
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
var jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;
var $ = require("jquery")(window);
const app = express();
app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function(req, res){
res.render("home", {years: years, comp: comp, placing: placing});
});
app.listen("3000", function(){
console.log("Server started on port 3000");
});
EDIT:
I needed a webserver to install node.js on.

Webpack with Express application generator

I am totally new to Expressjs (Nodejs) and I am using "Express application generator" here is a link. I am building simple website and using (Embedded JavaScript templating / EJS) and I want to add webpack to my app.
Here is my project structure.
Here is my app.js
var express = require('express');
var path = require('path');
var logger = require('morgan');
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// set path for static assets
app.use(express.static(path.join(__dirname, 'public')));
// routes
app.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('404 page.');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// render the error page
res.status(err.status || 500);
res.render('error', {status:err.status, message:err.message});
});
module.exports = app;
Does anyone have an idea how to do it, some example or anything that would help me?
Thanks everyone
Webpack is for single page application. There is only one index.html as the
hook, all the front-end contents will be generated by js files and bundled together by webpack then attached to the html hook.
If you use ejs or other template engine, you don't need webpack bundling your scripts, since you can split and load the scripts in your ejs files.
And your app.js and other Express things are backend things which run on your server, they don't need to be bundled or manipulated at all, you can do whatever you want, since those are on your server not users' browsers.
so just start to code your application.

Node.js/express.js default routing changes not being seen in ubuntu

EDIT ------------
so I figured out the issue, restarting and reloading nginx didn't have any effect, but if I stoped the nginx instance, then restarted it, any changes I made to the server files took effect. It's great that I figured it out, but could anyone give me some insight into why this is? It's better if I understand why this was happening. Any changes I made to the client side files such as the html files took affect immediately, it was only the server files that I had to stop then restart the nginx instance for it to take affect.
ORIGINAL POST BELOW----------------------
Any changes I make to the server side files of my deployed Node.js app with express.js isn't being seen by ubuntu. Basically, I have a mean app deployed on ubunut, it is a multipage page app, with only one of those pages having partials, so i use my routes.js
to catch the routes and send them to my main.js file to tell express and node which html or ejs file to load.
I made changes to the version on my computer so that all other routes would go to a certain html, it works great. But I pushed my changes to github, then pulled them in my ubuntu instance, and it's not working. All other changes I made to the project during this time that were pushed with it have taken affect. But, it's like ubuntu isn't letting node see any changes to the routes.js file, the code is there, I've even altered it with 'vim' from my terminal, but any changes I make, even ones that should break it, aren't seen by node. And going to an unexpected route displays the 'cannot GET...' page.
I've wracked my brain, but i'm stumped, the code is there and I can change it, I've altered html pages via vim to test it. But both, the routes.js file that handles my routing and my server.js file aren't reflecting my changes, even when I change things that should break it. Any ideas? Let me know if you need anymore info, i've included my files below. Also, I use nodemon so that it restarts automatically anytime changes are made
SERVER.JS FILE -------------------------------
var express = require('express'),
app = express(),
path = require('path'),
bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, './client')))
app.use(express.static(path.join(__dirname, './client/views')))
app.use(express.static(path.join(__dirname, './bower_components')))
app.set('views', path.join(__dirname, './client'));
app.set('view engine', 'ejs');
require('./server/config/routes.js')(app)
var port = 8000
app.listen(port, function(){
console.log('Server on port: ' + port)
})
ROUTES.JS FILE -----------------------------
var Main = require('../serverControllers/main.js')
module.exports = function(app){
app.get('/', Main.main)
app.get('/contact', Main.contact)
app.get('/algorithms', Main.algorithms)
app.get('/projects', Main.projects)
app.get('*', Main.other)
app.use(Main.other)
}
MAIN.JS FILE ----------------------
module.exports = {
main: function(req, res){
res.render('index')
},
contact: function(req, res){
res.render('contact')
},
algorithms: function(req, res){
res.render('algorithms')
},
projects: function(req, res){
res.render('projects')
},
other: function(req, res){
res.render('default')
},
}

Acessing public static files from routes folder in express

I'm trying to access a static 'home.html' file from the public folder. The architecture of the app is:
public
home.html
routes
index.js
views
myapp.js
myapp.js:
var express = require('express');
var path = require('path');
var routes = require('./routes/index');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
index.js:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/about', function(req, res, next){
res.sendFile(__dirname + '/home.html');
});
module.exports = router;
The main problem I'm having is I'm unable to load the home.html file at '/about'. The "__dirname" in index.js is pointing to the routes folder, and I've tried concatenating '/../' to move up a directory, but I just get a 403 Forbidden Error. I suppose I could put the home.html file in the routes directory, but I really want to figure out how to solve the underlying problem. Of course, rendering the jade file from the views folder at '/' works perfectly fine. Thank you in advance for your help and expertise.
You are trying to use it in the wrong way. The reason that you get the forbidden error is that the clients shouldn't be able to access folders outside the static folder that you have selected.
What you can do is to select multiple static directories, like Setting up two different static directories in node.js Express framework
Though I recommend that you just place all your publically available files in the same directory.

How to use expressjs with connect?

var express = require('express'),
routes = require('./routes'),
http = require('http'),
path = require('path'),
fs = require('fs');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.json());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
I'm getting the error Most middleware (like json) is no longer bundled with....
I've npm installed connect in the same folder.
But how do i use it?
I couldn't find any combined tutorial on connect & express, they either talk about connect or express.
Quoting from the Express.js's middleware documentation,
As of 4.x, Express no longer depends on Connect. All of Express' previously included middleware are now in separate repos. Please view the list of middleware. The only included middleware is now express.static().
So, to use json middleware, you need to include the body-parser in the package.json and then use like this
var bodyParser = require('body-parser');
app.use(bodyParser.json());

Categories

Resources