I am trying to setup Express to work with Backbone and pushState, but I'm not sure how to handle the routing. I've tried adding a middleware function (based on https://gist.github.com/3402977) to handle any undefined routes by inserting the # into the url, but it seems like the middleware is never getting called:
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('yadda yadda'));
app.use(express.session());
app.use(app.router);
// This should handle undefined routes.
app.use(function(err, req, res, next){
// Isn't getting called.
newUrl = req.protocol + '://' + req.get('Host') + '/#' + req.url;
res.redirect(newUrl);
});
app.use(express.static(path.join(__dirname, 'public')));
});
Currently, whenever I visit an route that I don't define in Express (http://localhost:3000/test/foo), it gives me a Could not GET /test/foo error. I would like it to redirect to http://localhost:3000/#/test/foo so that Backbone can handle the routing for permalinks and whatnot. What am I missing?
For future generations who land here:
The answer is that his middleware should be before the app.use(app.router); line.
Related
I am trying to setup a base for a MEAN application. I created the new project using Angular CLI, added Express.js, MongoDB modules to the application. In the app.js file I have the following configuration:
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var path = require("path")
var app = express();
var conf = require('./config/conf');
var server = require('http').Server(app);
var mongoDB = require('./adapters/mongodb')
var mongoClient = new mongoDB(conf);
app.use(bodyParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,__setXHR_');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
mongoClient.connect(function (dbconn) {
app.dbconn = dbconn;
app.conf = conf;
console.log("************************************************************");
console.log(new Date() + ' | CRUD Server Listening on ' + conf['web']['port']);
console.log("************************************************************");
server.listen(conf['web']['port']);
var Routes = require('./routes/http-routes');
new Routes(app);
});
I setup a hello world route for now and no changes done to the angular sources, which means I would land at the Angular default starting page. But I cant land at the page but instead a white screen page. However, I can access the routes using Postman. I do ng build and then node app.js to run the application. What am I doing wrong?
You should use the Express way to handle routes
First
const router=express.Router();
Then let's suppose you have a file using only authentication routes
const authentication = require('./routes/authentication')(router);
To conclude, you only have to do :
app.use('/authentication', authentication);
This allows a better divison of your routes
You 'll use your routes this way
module.exports= (router)=>{
router.get('/',(req,res)=>{
res.json(message:'Hello World');
});
return router;
To set angular routes you need the router module, for more details read the documentation
You serve only index.html from your Angular App. But you need also serve assets, css and javascript. Easiest would be something like this (but you need to adjust directory names:
app.use('/js', express.static(path.resolve(__dirname, 'dist/js')));
app.use('/css', express.static(path.resolve(__dirname, 'dist/css')));
app.use('/assets', express.static(path.resolve(__dirname, 'dist/assets')));
I have web application which is developed using ejs + angularJs 1.0 and running in node server. Since these ejs + angular provides only static files, I want to make my app running in webserver. Currently the URL mapping is done in node app.js, hence if we load the URL it renders the html from the ejs. For more information, I have added node app.js configuration:
app.set('title', wsConfig.title);
app.use(bodyParser.json());
app.engine('.html', ejs.__express);
app.set('view engine', 'ejs');
app.use(express.static('./public'));
app.set('views', path.join(__dirname, 'public')); // Set the views path
app.use(function(req, res, next) {
if (req.url.substr(-1) == '/' && req.url.length > 1)
res.redirect(301, req.url.slice(0, -1));
else
next();
});
app.get('/', function(req, res) {
res.render('login', { title: wsConfig.title });
});
app.get('/home', function(req, res) {
res.render('index', { title: wsConfig.title });
});
Hence I need to build a dist folder with js and rendered ejs files instead using node server for rendering. So that I will deploy this dist directory in web server. I thought of using webpack to accomplish this. Please give our suggestions.
I was working on Angular app with routing (NodeJs as backend). Routing through pages works fine but when I try to reload page it gives 'cannot load path /home'. I browsed through and got to few solutions like THIS.
My code is
app.get('*', function (req, res) {
res.sendFile('mypath/index.html');
});
But this loads up blank page. Is there any way I can solve this issue?
This us how my server.js looks like
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var port = process.env.PORT || 8080; // set our port
var staticdir = process.env.NODE_ENV === 'production' ? 'dist.prod' : 'dist.dev'; // get static files dir
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json()); // parse application/json
//app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
//app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(express.static(__dirname + '/' + staticdir)); // set the static files location /public/img will be /img for users
// routes ==================================================
app.set('views', __dirname + '/app');
app.set('view engine', 'html');
require('./devServer/routes')(app); // configure our routes
// start app ===============================================
app.listen(port); // startup our app at http://localhost:8080
console.log('Starting sever on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
app.get('/', function (req, res) {
res.render('index', {
page: 'index'
}
});
then out this into your config,
app.set('views', 'directory where index.html is');
I am trying to understand how to include jade and handlebar exactly as I am trying to add angular js to my server that is also using jade for serving other web pages.
I heard of consolidate.js and this is my app.js code:
var engines = require('consolidate');
var exphbs = require('express-handlebars');
var app = express();
app.engine('jade', engines.jade);
app.engine('handlebars', engines.handlebars);
app.set('view engine', 'handlebars');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon(path.join(__dirname, 'public', 'img/favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser(config.cookieSecret.secret));
app.use(express.static(path.join(__dirname, 'public')));
How do I get the view engine setup for both? Also, how do I add the following into my code without affecting other links:
// Application UI route
app.get('*', function(req, res) {
res.render('indexer');
});
app.get('/templates/*', function(req, res) {
res.render('../client/templates/' + req.params[0])
});
I'm struggling to perform routing using Express in the ng-boilerplate structure.
I'd like to do it using HTML view files (as opposed to JADE).
Can anyone help provide examples of how to do this?
I keep getting Failed to lookup view xx errors when using app.get('/', function(req, res){
res.render('index');
});
Try to set your views directory:
var express = require('express');
var app = express();
app.configure(function() {
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views'); // <=== Where your HTML view files are present
app.set('view engine', 'jade'); //Your view engine to be set here
});
For detailed information:
Express API
Related Questions and answers