I'm trying to show 2 different Angular 2 apps through Node/Express route.
But my route only shows only the root's index.html even on the path of other route. I tried a lot of different things but nothing seem to work. Would appreciate any help in this.
UPDATE:
I solved the problem by replacing these codes in server.js:
But now the issue is my route url shows like this "http://localhost:3020/iot/#./". I changed the LocationStrategy from HashLocationStrategy to PathLocationStrategy in app.module.ts but then the route doesn't work. How do I remove the '#' tags from my urls. If any one could suggest.
Hope my answer would help someone facing the same problem.
//View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use('/', express.static(path.join(__dirname,'/client/dist/')));
app.use('/mwc', express.static(path.join(__dirname,'/mwc/dist/')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use('/', index);
app.use('/mwc', mwc);
app.use('/api/vi/', todos);
with just this
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use('/', express.static('client/dist'));
app.use('/mwc', express.static('mwc/dist'));
app.use('/iot', express.static('iot/dist'));
app.use('/canteen', express.static('canteen/dist'));
app.use('/api/vi/', todos);
& including the following code in my angular apps 'app.module.ts' & changing base href from "/" to "./" in index.html file.
import { CommonModule, APP_BASE_HREF, LocationStrategy, HashLocationStrategy} from '#angular/common';
providers: [
{ provide: APP_BASE_HREF, useValue: './' },
{ provide: LocationStrategy, useClass: HashLocationStrategy }
],
Below is the previous code:
server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var todos = require('./routes/todos');
var mwc = require('./routes/mwc');
var app = express();
var router = express.Router();
//View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use('/', express.static(path.join(__dirname,'/client/dist/')));
app.use('/mwc', express.static(path.join(__dirname,'/mwc/dist/')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use('/', index);
app.use('/mwc', mwc);
app.use('/api/vi/', todos);
app.listen(3020, function(){
console.log("Server started on port 3020...");
});
Related
I am facing some errors while integrating hbs and express in node js
content from layouts& partials are getting not loaded ,even though they are connected to
app.js , layout is loading when we move it into root of view.its not loading when its in a folder inside view.
When i move layouts.hbs to root it starts to load but partials are not loading since its inside a folder.(error:The partial my_partial could not be found)
when i googled about partial i found that hbs.registerPartial(path.join(__dirname, "/views/partials")); could be used but it showed an error that hbs.registerPartial is not a function.
so anyone please suggest me what to do
I expect solution for
How can i load default layout and partials by creating folders named layouts and partials respectively
-- views
-- partials
partial1.hbs
partial2.hbs
-- layouts
layout.hbs
app.js
error.hbs
//app.js
var createError = require('http-errors');
var express = require('express');
const hbs = require('express-handlebars');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
hbs.registerPartial(path.join(__dirname, "/views/partials"));
app.engine("hps", hbs.engine({ extname: "hbs", defaultLayout: "layout", layoutsDir: path.join(__dirname, 'views', "layout"), partialsDir: path.join(__dirname, 'views', "partials") }))
console.log(path.join(__dirname, 'views', "layout"))
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I am a newbie to use express and as a result am bungling my way through making this web app.
I have my routes in a different file called route.js inside a module.export, and I manage all this inside app.js and I want to be able to serve a HTML page and keep it in the module. I've done so using sendFile but it doesn't serve the CSS and JS as well. What can I do to fix this?
app.js
//setup
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 index = require('./routes/index');
var users = require('./routes/users');
var app = express();
var port = process.env.PORT || 3000;
var mongoose = require('mongoose');
var flash = require('connect-flash');
var passport = require('passport');
var session = require('express-session');
var path = require('path');
//db
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport')(passport);
// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
app.set('view engine', 'ejs');
//routes
//app.use('/', index);
//app.use('/users', users);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//passport
app.use(session({secret: 'secret'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
//routes
require('./app/routes.js')(app, passport);
// catch 404 and forward to error handler
/*app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});*/
// error handler
/*app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});*/
module.exports = app;
//launch
app.listen(port);
console.log('Website starting on port ' + port);
routes.js
module.exports = function(app,passport) {
...
//--timesheet section---
app.get('/timesheet', function(req, res) {
var path = require('path');
res.sendFile(path.resolve('public/timesheet.html'));
});
...
}
You want to use a view engine and a static directory. You have some of the code already.
Your view engine using .ejs:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
And you can define your static and specify a path prefix:
app.use('/assets', express.static(path.join(__dirname, 'public')));
In your views directory, put your htmls with .ejs extension, such as timesheet.ejs. You can then create an assets directory for your css/js/image files and reference them in your timesheet.ejs using /assets/style.css.
Finally, in your route, you'll want to render the template:
res.render('timesheet')
I try to use multer to store locally files. I just want to run the sample but my app.post route is not triggered.
here is my simple code (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 multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get("/", function(req, res){
res.render("index", { title: 'Express' });
});
app.get("/upload", function(req, res) {
res.render("upload");
});
app.post('/upload', upload.single('upl'), function (req, res) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
console.log(req.file);
})
...// regular code generated by express
and my jade view is ad follow (upload.jade)
extends layout
block content
h1= title
p Welcome to upload form
form(method="post",enctype="multipart/form-data",action="/upload")
p
input(type="text",name="title", placeholder="title")
p
input(type="file",name="upl")
p
input(type="submit")
There is something I am missing but don't see what.
Thx
Ok, sorry for asking this question.
I was focused on the js file where the indentation wasn't correct in my jade file. form was empty. All p's must be inside the form.
This is html page.I'm calling this page from node.js server i.e, app.js.Here I'm unable to load socket.io.js,bootstrap.js,bootstrap.css pages.
My index.html:
<html>
<script type="text/javascript" src="/javascripts/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type ="text/javascript" src="/javascripts/bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="/stylesheets/bootstrap.css" />
<div id="progressbar">
</div>
<script>
var socket = io('http://localhost:8085');
socket.on('connect', function(){});
socket.on('message', function(data){
$('#progressbar').progressbar({
maximum: 100,
step: JSON.parse(data).percent
});
});
socket.on('disconnect', function(){});
</script>
</html>
My app.js code :
var app = express ();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(8085, function(){
console.log('listening on *:8085');
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
//res.send('Hello World!');
});
In firebug,I'm facing this
You have set up incorrect paths for static files.
In your case, you'll need to use this:
app.use('/javascripts', express.static(__dirname + '/javascripts'));
app.use('/stylesheets', express.static(__dirname + '/stylesheets'));
Now, whatever files are in javascripts and stylesheets folders will load as static files.
Your current method of using static files:
app.use(express.static(path.join(__dirname, 'public')));
This will load everything that's beneath public folder as static files, so you would need to move the javascripts and stylesheets folders there if you want that to work.
change your view engine to html and modify the code like below :
app.set('views', path.join(__dirname, 'public'));
app.set('view engine', 'html');
and change the sendfile method :
res.sendFile(path.join(__dirname, '../YOUR_FOLDER_NAME/public', 'index.html'));
EDITED::
change the index.html file:
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<link rel="stylesheet" type="text/css" href="stylesheets/test.css" />
This is the app.js. (based on #Andrius' solution) I was able to make it running on http://localhost:8085. index.html stays the same.
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(8085, function(){
console.log('listening on *:8085');
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//test
app.use('/javascripts', express.static(__dirname + '/javascripts'));
app.use('/stylesheets', express.static(__dirname + '/stylesheets'));
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', routes);
//app.use('/users', users);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
//res.send('Hello World!');
});
I'm trying to load this helper on my Express / Handlebars project, but, I can't manage to make it work...
Here is my app.js
var express = require('express'),
exphbs = require('express-handlebars');
var app = express();
app.engine('handlebars', exphbs({
defaultLayout: 'main',
helpers: require('handlebars-form-helpers').helpers
}));
app.set('view engine', 'handlebars');
app.get('/', function (req, res) {
res.render('home');
});
app.listen(3000);
And here is the page when I try to load it
Kind of new with Handlebars integration with Express, so, I can't manage to figure it out...
This should work:
var exphbs = require('express-handlebars'),
handlebars = require('handlebars'),
helpers = require('handlebars-form-helpers').register(handlebars);
var hbs = exphbs.create({
helpers: helpers,
defaultLayout: 'main'
});
app.engine('.hbs', hbs.engine);
app.set('view engine', '.hbs');
You can find more info here: https://github.com/ericf/express-handlebars/blob/master/examples/advanced/server.js