Angular2 + ExpressJs <app-root> dosen't load. - javascript

I did read all the other topics but none of the solutions solved my problem.
I write npm start and the server is working as it should but app-root does not it seems like it does not load the client (Angular 2 app).
I just get an empty html page with:
Loading...
(look at my html file down the page)
any idea what can cause it - or any suggested solution ?
Thank you.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose')
//Set up default mongoose connection
var mongoDB = 'mongodb://localhost/beatblocks';
// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise;
mongoose.connect(mongoDB, function(err) {
if (err){
console.log("error connecting to db...")
}
console.log("connected to database...");
});
// Load Songs Model
require('./models/songs');
const songs = mongoose.model('songs');
// Load Locations Model
require('./models/locations');
const locations = mongoose.model('locations');
// Load users Model
require('./models/users');
const users = mongoose.model('users');
var routeIndex = require('./routes/index');
var routeSongs = require('./routes/songs');
var routeUsers = require('./routes/users');
//var routeLocations = require('./routes/locations');
var app = express();
var router = express.Router();
// Set Static Folder
app.use(express.static(path.join(__dirname, 'views')));
app.use(express.static(path.join(__dirname, '/client/dist')));
app.use(express.static(path.join(__dirname, 'client/src')));
//View Engine
app.engine('ejs', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', routeIndex);
app.use('/songs', routeSongs);
app.use('/users', routeUsers);
//app.use('/locations', routeLocations);
module.exports = app;
www.js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('beatblocksweb:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
app.listen(port, function(){
console.log('Server started on port '+port);
});
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
my index.html :
<html>
<head>
<title>Beat Blocks</title>
</head>
<body>
<app-root>Loading...</app-root>
<app-header></app-header>
</body>
</html>
my project :

Related

reload/reload.js route is not working

reload/reload.js route is not working
I'm using express-generator app code template to create my node applications
I also followed github issues information for this package
https://github.com/alallier/reload/issues/56#issuecomment-288393265
In this comment he said to create a custom route to listen for this file
app.get('/reloader', (req, res) => {
res.type('text/javascript')
res.sendFile(require.resolve('reload/lib/reload-client'))
});
But, when i tried this reload is not working and in console an error exception occurring:
Uncaught DOMException: Failed to construct 'WebSocket': The URL's
scheme must be either 'ws' or 'wss'. 'http' is not allowed.
at new WrappedWebSocket (:164:21)
Here is my code (bin/www)
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var reload = require('reload');
var debug = require('debug')('node1:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
reload(app); // here i'm using reload module
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
I resolved this issue by using reload(app) in ./app.js instead of ./bin/www
It is working fine in app.js file (even if i change the location of this statement) but, in ./bin/www file it is not working.
Code (./app.js):
var express = require('express');
var path = require('path');
var reload = require('reload');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressHandlebars = require('express-handlebars');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
reload(app); // Init Reload module

NodeJs HTTPS connection with express generator

I've created an app using the express generator which all works okay but I now want to run the app with HTTPS, I've tried to configure the node server file in /bin/www to the following:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var debug = require('debug')('****:server');
var https = require('https');
var fs = require('fs');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3001');
app.set('port', port);
var options = {
path: '../app',
port: 443,
key: fs.readFileSync('/var/www/vhosts/keys/wildcard.****.com.key'),
cert: fs.readFileSync('/var/www/vhosts/keys/wildcard.****.com.crt')
}
/**
* Create HTTPS server.
*/
var server = https.createServer(options);
But I can no longer access my app when pointing it to https://
try this out:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.cert')
};
// Create a service (the app object is just a callback).
var app = express();
// Create an HTTP service.
http.createServer(app).listen(80);
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);
and create a self-signed certificate. How ? follow this link http://docs.nodejitsu.com/articles/HTTP/servers/how-to-create-a-HTTPS-server
I solved this issue modifing after creation with express-generator the bin/www file and renamed it as wwws. Then in package.json I change the "source" attribute pointing the new script.
...
"scripts": {
"start": "node ./bin/wwws"
},
...
In wwws I use an https server instead of an http and then I redirect the http requests.
Here my new wwws file. I removed the http lines in the middle of www file and I added the new server section at the end.
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('phishsense:server');
var http = require('http');
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
// Add HTTPS Section
var fs = require('fs');
var https = require('https');
var http_port = normalizePort(process.env.PORT || '8080');
var https_port = process.env.PORT_HTTPS || 8443;
var options = {
key : fs.readFileSync('server.key'),
cert : fs.readFileSync('server.crt')
};
app.set("port",https_port);
/*
° Create HTTPS server.
*/
server = https.createServer(options, app).listen(https_port, function () {
console.log('Magic happens on port ' + https_port);
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(https_port);
server.on('error', onError);
server.on('listening', onListening);
// Redirect from http port to https
http.createServer(function (req, res) {
res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url });
console.log("http requet, will go to >> ");
console.log("https://" + req.headers['host'].replace(http_port,https_port) + req.url );
res.end();
}).listen(http_port);
This works for me and lets the structure created by express-generator untouched.

Manipulating Cookies before serving

Scenario
I have a simple NodeJS server using the Express framework. I have some ReactJS pages that I need to serve. No Isomorphic for now.
Before serving, I want to check if the user has a particular cookie and then based on that I want to create a new cookie.
What I tried
Here is the code for my server.js file.
var express = require("express");
var app = express();
var Cookies = require("cookies");
app.use(function(req, res){
var cookies = new Cookies( req, res);
var userCookie = cookies.get("sso");
var isLoggedIn = cookies.get("isLoggedIn");
if(userCookie !== undefined && isLoggedIn === false){
cookies.set("isLoggedIn", true);
}
});
app.use(express.static(__dirname + '/build'));
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
});
So I am using express.static for serving static files from my build folder.
I tried moving the app.use(express.static(__dirname + '/build')); line above the previous app.use, but then the code never enters the cookies section.
I tried this simple thing. Even this didn't worked. I can see log hello, but the website isn't working.
var express = require("express");
var app = express();
app.use(function(req, res){
console.log("hello");
});
app.use(express.static(__dirname + '/build'));
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
});
There's a problem with your use of cookies. You're checking if isLoggedIn, the cookie value, === false, a boolean value. But cookies are always strings, so the comparison will always be false and you'll never set isLoggedIn to "true".
If your update your code to treat the values as strings it might work. Try something like this:
if(userCookie !== undefined && isLoggedIn !== "true"){
cookies.set("isLoggedIn", "true");
}
As jeremy's answer pointed out, I was using the cookies the wrong way. But that wasn't the core problem. If code would have run, express server would have thrown error. The real problem was that i wasn't calling the next middleware in the application’s request-response cycle. According to the docs
Middleware is a function with access to the request object (req), the
response object (res), and the next middleware in the application’s
request-response cycle, commonly denoted by a variable named next.
I wasn't calling the next.
So the updated running code is:
var express = require("express");
var app = express();
var Cookies = require("cookies");
app.use(function(req, res, next){
var cookies = new Cookies( req, res);
var userCookie = cookies.get("sso");
var isLoggedIn = cookies.get("isLoggedIn");
if(userCookie !== undefined && isLoggedIn !== "true"){
cookies.set("isLoggedIn", "true",{ httpOnly: false } );
}
next();
});
app.use(express.static(__dirname + '/build'));
var port = process.env.PORT || 8142;
app.listen(port, function() {
console.log("Listening on " + port);
});

Node JS Express all requests showing 404

All requests are showing GET / 404 8.128 ms-13 in console.
I have posted the code below, there is no error in the code. I can run other NodeJS applications. But this is showing 404 in console. It is not even showing the fav icon. It worked once showing Cannot GET / error and the fav icon was visible at that time.
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var logger = require('morgan');
var port = process.env.PORT || 8001;
var four0four = require('./utils/404')();
var environment = process.env.NODE_ENV;
app.use(favicon(__dirname + '/favicon.ico'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use('/api', require('./routes'));
console.log('About to crank up node');
console.log('PORT=' + port);
console.log('NODE_ENV=' + environment);
switch (environment){
default:
console.log('** DEV **');
app.use(express.static('./src/client/'));
app.use(express.static('./'));
app.use(express.static('./tmp'));
app.use('/app/*', function(req, res, next) {
four0four.send404(req, res);
});
app.use('/*', express.static('./src/client/index.html'));
break;
}
app.listen(port, function() {
console.log('Express server listening on port ' + port);
console.log('env = ' + app.get('env') +
'\n__dirname = ' + __dirname +
'\nprocess.cwd = ' + process.cwd());
});
According to http://expressjs.com/starter/static-files.html I think that your route here app.use('/*', express.static('./src/client/index.html')); will use ./src/client/index.html as the base path and append whatever you provide to find a file. For example
/some-file will look for ./src/client/index.html/some-file which is obviously not existed
In case you want to understand it more, the static middleware use https://github.com/pillarjs/send internally to stream file
So you can do this
app.use('/*', express.static('./src/client'));
It will, by default, set / to src/client/index.html, you can change that behaviour by setting index option as specified here https://github.com/expressjs/serve-static
If you want to redirect /* to ./src/client/index.html do this
// first set the static middleware
app.use('/public', express.static('./src/client'));
// then use redirect
app.get('/*', function(req, res, next){
res.redirect('/public/index.html');
});
This setup will redirect everything to public/index.html. If you want to add APIs or other routes, put it before the app.get('/*')

nodejs server app having type errors like path.join

As i am running my server.js ,it starts of pretty well with the main staring page being loaded up but there i have to enter a nickname to enter any room. As i enter the name and click on the Create chat room button it shows this type of error. Since i am new to building node.js apps ,please help me to solve this issue..The server code is provided below..
TypeError: Arguments to path.join must be strings
at path.js:360:15
at Array.filter (native)
at exports.join (path.js:358:36)
at exports.send (/home/gauz/Desktop/hackview-master/node_modules/connect/lib/middleware/static.js:129:20)
at ServerResponse.res.sendfile (/home/gauz/Desktop/hackview-master/node_modules/express/lib/response.js:186:3)
at app.get.req.session.nick (/home/gauz/Desktop/hackview-master/server.js:71:9)
at callbacks (/home/gauz/Desktop/hackview-master/node_modules/express/lib/router/index.js:272:11)
at param (/home/gauz/Desktop/hackview-master/node_modules/express/lib/router/index.js:246:11)
at param (/home/gauz/Desktop/hackview-master/node_modules/express/lib/router/index.js:243:11)
at pass (/home/gauz/Desktop/hackview-master/node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (/home/gauz/Desktop/hackview-master/node_modules/express/lib/router/index.js:280:5)
at Object.Router.middleware [as handle] (/home/gauz/Desktop/hackview-master/node_modules/express/lib/router/index.js:45:10)
at next (/home/gauz/Desktop/hackview-master/node_modules/connect/lib/http.js:204:15)
at next (/home/gauz/Desktop/hackview-master/node_modules/connect/lib/middleware/session.js:322:9)
at /home/gauz/Desktop/hackview-master/node_modules/connect/lib/middleware/session.js:341:9
at /home/gauz/Desktop/hackview-master/node_modules/connect/lib/middleware/session/memory.js:52:9
at process._tickCallback (node.js:415:13)
Server Code:
var express=require('express'),
app = express.createServer(),
sharejs = require('share'),
sharejsOptions={db:{type:'none'}};
/*
var express=require('express');
var app = express();
var sharejs = require('share');
var sharejsOptions={db:{type:'none'}};
*/
var env = process.env.NODE_ENV;
//if we were provided redis options, use them for persistence
//the if case is for developers not using redis
if(process.env.redis_port){
sharejsOptions.db= {
type: 'redis',
prefix: '',
port: process.env.redis_port,
auth: process.env.redis_auth || null
}
};
sharejs.server.attach(app, sharejsOptions);//attach to express
if (env !== 'production')
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/public'));
app.use(express.favicon(__dirname+"/public/favicon.ico"));
app.use(express.cookieParser());
app.use(express.session({secret:"SuperSecretSessionKey"}));
//heroku support
var port = process.env.PORT || 8000;
app.listen(port);
console.log('App running on port : '+port);
//webRTC Stuff
var webRTC = require('webrtc.io').listen(app);
require('./rtc.js')(webRTC);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/public/room.html');
});
/** Create a new random room */
app.get('/join',function(req,res){
var roomName=req.query.nickname.split('#')[1];
if(!roomName)
roomName=getRandomRoom();
var nickName = req.query.nickname.split('#')[0];
req.session.nick = nickName;
res.redirect('/room/'+roomName);
});
var getRandomRoom = function(){
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
return randomstring;
}
app.get('/room/:roomName',function(req,res){
if(req.session.nick || req.query.asknick){
//if a person has his nickname set, let him reach that
res.sendfile(__dirname+'/public/room.html');
}
else{
//make sure he/she is asked a username
res.redirect('/room/'+req.params.roomName+'?asknick=yes');
}
});
app.get('/setnick',function(req,res){
res.cookie('nick',req.query.nick);
req.session.nick = req.query.nick;
res.send('');
});
app.get('/debug',function(req,res){
res.json(req.session);
});
According to this GitHub issue, you'll need to replace calls to res.sendfile from this:
res.sendfile(__dirname+'/public/room.html');
to this:
res.sendfile('/public/room.html', { root: __dirname });

Categories

Resources