How to configure dynamic routes with express.js - javascript

I have a route.js which looks like this:
module.exports = function(app) {
app.get('/tip', function(req, res) {
res.render("tip");
});
app.get('/article', function(req, res) {
res.render("article");
});
app.get('/article1', function(req, res) {
res.render("article1");
});
app.get('/article2', function(req, res) {
res.render("article2");
});
app.get('/article3', function(req, res) {
res.render("article3");
});
app.get('/modules/:name', function(req, res) {
var name = req.params.name;
res.render('modules/' + name);
});
app.get('/modules/esaver/:name', function(req, res) {
var name = req.params.name;
res.render('modules/esaver/' + name);
});
};
Considering i have over 200 different routes to create, i would end up with stuff like 'article1', 'article2' etc
and my app.js is like:
var express = require('express')
,http = require('http')
,fs = require('fs')
,path = require('path');
var app = express();
html_templates = __dirname + '/html_templates';
app.set('views', html_templates + '/views');
app.set('view engine', 'jade');
app.use('/Core', express.static(__dirname + '/Core'));
app.listen(3000, function () {
console.log("express has started on port 3000");
});
require('./html_templates/controller/routes.js')(app);
Is there any dynamic way to create this?

I would do the same thing you did for /modules/:name
app.get('/article/:id', function(req , res){
res.render('article' + req.params.id);
});
It would be more meaningful from a rest point of view.
If you cannot do it for any particular reason you might want to do something like:
var articlesEndpoints = ['/article2', '/article3'];
articlesEndpoints.forEach(function(name) {
app.get(name, function(req, res) {
res.render(name);
});
});
Is this what you meant?

Finally got it working..
In cases where I got, article1, article2 etc:
app.get('/:name(article|article2|article3)?', function(req, res) {
var name = req.params.name;
res.render(name);
});
In cases where I got multi level url, I created a custom function:
function geturl(url) {
app.get('/' + url + '/' + ':name', function(req, res){
var name = req.params.name;
res.render(url + '/' + name);
});
};

There are many ways to implement dynamic express routes. It depends to a great extent on the structure you have implemented in your project, here I leave an example of dynamic routes and I hope it will be useful.
RouterService.js
module.exports = (function(myCustomRoutes) {
let express = require('express');
let router = express.Router();
let methods = Object.keys(myCustomRoutes); // getting methods ('get', 'post'... etc)
let routesMethod = null;
let url = null;
for(i in methods) {
routesMethod = Object.keys(myCustomRoutes[methods[i]]);
for(j in routesMethod) {
url = '/' + routesMethod[j];
url += '/:' + myCustomRoutes[methods[i]][routesMethod[j]].params.join('/:');console.log(url);
router[methods[i]](url, myCustomRoutes[methods[i]][routesMethod[j]].controller);
}
}
return router;
})();
CustomRoutes.js
module.exports = (function() {
let routes = {get: {}, post: {}};
let routerService = require('./RouterService');
// GET: /dynamic1
routes.get.dynamic1 = {
params: [],
controller: function(req, res, next) {
res.send('route 1');
}
};
// GET: /dynamic2/:param1
routes.get.dynamic2 = {
params: [':param1'],
controller: function(req, res, next) {
res.send('route 2');
}
};
// POST: /dynamic3/:param1/:param1
routes.post.dynamic3 = {
params: ['param1', 'param2'],
controller: function(req, res, next) {
res.send('route 3');
}
};
/*
* Export a router with paths
* GET: /dynamic1
* GET: /dynamic2/:param1
* POST: /dynamic3/:param1/:param1
**/
return routerService(routes);
})();
app.js
let express = require('express');
let app = express();
/*
* Option 1
* GET: /dynamic1
* GET: /dynamic2/:param1
* POST: /dynamic3/:param1/:param1
**/
app.use(require('CustomRoutes')());
/*
* Option 2
* GET: /api/v1/dynamic1
* GET: /api/v1/dynamic2/:param1
* POST: /api/v1/dynamic3/:param1/:param1
**/
app.use('/api/v1', require('CustomRoutes')());

Here is what I did to create dynamic APIs while I am in control over which API allows access to which methods. To maintain the APIs from now on, you can just edit the APIs array.
const APIs = [
{
route: 'order',
methods: ['get', 'post']
},
{
route: 'item',
methods: ['get']
},
]
APIs.forEach(api => {
api.methods.forEach(method => {
app[method]('/' + api.route, (req, res) => require('./routes/' + api.route)[method](req, res))
})
})

Here are a couple of other solutions:
app.get(^\/article(\d{1,3})?\/?$, function(req, res, next) {
var n;
if (req.params[0])
n = parseInt(req.params[0], 10);
if (!n || (n > 0 && n < 900))
res.render('article' + (n ? n : ''));
else
next();
});
or use app.all for the first solution or use a generic middleware:
app.use(function(req, res, next) {
var m = ^\/article(\d{1,3})?\/?$.exec(req.url);
if (m) {
var n;
if (m[0])
n = parseInt(m[0], 10);
if (!n || (n > 0 && n < 900))
return res.render('article' + (n ? n : ''));
}
next();
});

I create a new module called: jadewalker. It will create router code automatically.
We can simply add a jadewalker comment to your jade Or pug file.
//- jadewalker=/b,/b/:id
doctype html
html
title b.jade
body
p b.jade
p params: #{params.id}
And add this module to our app. That's all.
var app = require('koa')()
var router = require('koa-router')();
router = require('jadewalker')(router, path.join(__dirname, 'views'));
app.use(router.routes());
We can visit our jade file by the URL http://localhost:3000/b/abc. (^∀^)

It's work on my project
routesPath = path.join(__dirname, 'routes');
fs.readdirSync(routesPath).forEach(function(file) {
require(routesPath + '/' + file)(app);
});

Related

Edit and create HTML content using node.js

I want to create html content that looks something like this using node.js.
<div class="outputs">
...
</div>
I have the following code:
var mongoose = require("mongoose");
var express = require("express");
var bodyParser = require("body-parser");
var Url = require("./models/Url");
var shortId = require("shortid");
var http = require("http");
var app = express();
var { JSDOM } = jsdom;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(process.env.MLAB_URI);
app.get("/urls", (req, res, next) => {
Url.find({}, function(err, data) {
res.json(data);
console.log(data.length);
});
});
app.get("/deletebase", (req, res, next) => {
Url.deleteMany({}, function(err, data) {
res.json(data);
});
});
app.use(express.static(__dirname + "/"));
app.get("/:shortUrl", function(req, res, next) {
Url.findOne({ shortUrl: req.params.shortUrl }, function(err, findUrl) {
if (err) console.log(err);
if (!findUrl) {
return next({ status: 400, message: "unknown shorturl" });
}
res.redirect(findUrl.longUrl);
});
});
app.post("/", function(req, res) {
var url = new Url(req.body);
var hostname = req.headers.host;
var expression = /[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()#:%_\+.~#?&//=]*)?/gi;
var regex = expression;
if (regex.test(url) === true) {
url.shortUrl = shortId.generate();
url.fullUrl = "https://" + hostname + "/" + url.shortUrl;
url.save(function(err, savedUrl) {
if (err) console.log(err);
res.redirect("https://" + hostname);
});
} else {
res.redirect("https://" + hostname);
}
});
var options = {
runScripts: "dangerously",
resources: "usable"
};
app.listen(3000, function() {
console.log("RUNNING");
});
I want to get length of the data and create that many div objects with longUrl and shortUrl objects in it. Also when database will be updated new div object should be created, and when I delete database information all the div elements should be deleted too, is this possible to do?
You should be using a templating engine for this the two most popular ones for Node.js are pug(formerly Jade) and hbs(Handlebars.js).
There are a lot of other template engines here you could consider.

Express js flow behavior

I need to understand how flow works in an Express app using Routes,
I have These Routes
app.use(require('./routes/reportsRouter'));
app.use(require('./routes/crewsRouter'));
app.use(require('./routes/api'));
app.use(require('./routes/filesRouter'));
Now in ./routes/crewsRouter I have th following Code
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
var url = req.url;
//..... Edit URL if Contains // empty parm
// crews//today; correct Url crews/all/today
// this give me a list of all jobs for all crews for today.
console.log("CrewsRouter: ", req.method + ".( " + url + " )");
next();
});
router.get('/crews', function(req, res) {
if (!req.params.key) { next(); }
res.render('crewsView',{
pageTitle:'All-Crews',
pageID:'crews',
crewInfo: {"aka": "all"},
reqOptions: ''
});
});
router.get('/crews/:leadId?/:options?', function(req, res) {....}
module.exports = router;
and in reportsRouter.js
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
// log each request to the console
console.log("ReportsRouter: ", req.method + ".( " + req.url + " )");
// continue doing what we were doing and go to the route
next();
});
router.get('/reports', function(req, res) {
//var data = req.app.get('appData')
res.render('reportsView',{
pageTitle:'Reports',
pageID:'reports'
});
});
module.exports = router;
The behavior I'm having is no matter what route I request
both of the route.use is running. Is this normal and what can i do to stop this behavior.
let crewsRouter = require('routes/crewsRouter');
...
app.use('/crews', crewsRouter);
app.use('/reports', reportsRouter);
# crews
...
router.get('/', function(req, res) {
... # this used to be your '/crews' handler
}
# reports
...
router.get('/', function(req, res) {
... # this used to be your '/reports' handler
}
You should probably be doing something like this:
app.use('/reports', require('./routes/reportsRouter'));
app.use('/crews', require('./routes/crewsRouter'));
app.use('/api', require('./routes/api'));
app.use('/files', require('./routes/filesRouter'));
And then in your reportsRouter:
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
// log each request to the console
console.log("ReportsRouter: ", req.method + ".( " + req.url + " )");
// continue doing what we were doing and go to the route
next();
});
router.get('/', function(req, res) {
//var data = req.app.get('appData')
res.render('reportsView',{
pageTitle:'Reports',
pageID:'reports'
});
});
module.exports = router;
And your crewsRouter:
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
var url = req.url;
//..... Edit URL if Contains // empty parm
// crews//today; correct Url crews/all/today
// this give me a list of all jobs for all crews for today.
console.log("CrewsRouter: ", req.method + ".( " + url + " )");
next();
});
router.get('/', function(req, res) {
if (!req.params.key) { return next(); }
res.render('crewsView',{
pageTitle:'All-Crews',
pageID:'crews',
crewInfo: {"aka": "all"},
reqOptions: ''
});
});
router.get('/:leadId?/:options?', function(req, res) {....});
module.exports = router;

Node.js : get cloudant variable form app.js file

I have the node js application on bluemix. I want to use the cloudant variable on app js from provider js.But it does not work. Please help me review it
app.js
/**
* Module dependencies.
*/
var express = require('express'),
routes = require('./routes'),
user = require('./routes/user'),
http = require('http'),
path = require('path'),
fs = require('fs'),
ibmbluemix = require('ibmbluemix'),
ibmpush = require('ibmpush');
var app = express();
var db;
var cloudant;
var fileToUpload;
var dbCredentials = {
dbName : 'my_sample_db',
dbProvider : 'provider'
};
var config = {
// change to real application route assigned for your application
applicationRoute : "http://demo.mybluemix.net"
//for test by postman.
};
// init core sdk
ibmbluemix.initialize(config);
var ibmconfig = ibmbluemix.getConfig();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/style', express.static(path.join(__dirname, '/views/style')));
//CORS middleware
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key,IBM-APPLICATION-SECRET,IBM-APPLICATION-ID,IBM-DEVICE-MODEL,IBM-DEVICE-TYPE,IBM-DEVICE-ID,IBM-DEVICE-PLATFORM-VERSION, IBM-DEVICE-NAME,IBM-REQUEST-CORRELATION-ID,X-REWRITE-DOMAIN');
next();
};
app.use(allowCrossDomain);
// development only
if ('development' == app.get('env')) {
app.use(errorHandler());
}
function initDBConnection() {
if(process.env.VCAP_SERVICES) {
var vcapServices = JSON.parse(process.env.VCAP_SERVICES);
// Pattern match to find the first instance of a Cloudant service in
// VCAP_SERVICES. If you know your service key, you can access the
// service credentials directly by using the vcapServices object.
for(var vcapService in vcapServices){
if(vcapService.match(/cloudant/i)){
dbCredentials.host = vcapServices[vcapService][0].credentials.host;
dbCredentials.port = vcapServices[vcapService][0].credentials.port;
dbCredentials.user = vcapServices[vcapService][0].credentials.username;
dbCredentials.password = vcapServices[vcapService][0].credentials.password;
dbCredentials.url = vcapServices[vcapService][0].credentials.url;
cloudant = require('cloudant')(dbCredentials.url);
// check if DB exists if not create
cloudant.db.create(dbCredentials.dbName, function (err, res) {
if (err) { console.log('could not create db ', err); }
});
db = cloudant.use(dbCredentials.dbName);
break;
}
}
if(db==null){
console.warn('Could not find Cloudant credentials in VCAP_SERVICES environment variable - data will be unavailable to the UI');
}
} else{
console.warn('VCAP_SERVICES environment variable not set - data will be unavailable to the UI');
}
}
initDBConnection();
app.get('/', routes.index);
function createResponseData(id, name, phone, attachments) {
var responseData = {
id : id,
name : name,
phone : phone,
attachements : []
};
attachments.forEach (function(item, index) {
var attachmentData = {
content_type : item.type,
key : item.key,
url : '/api/favorites/attach?id=' + id + '&key=' + item.key
};
responseData.attachements.push(attachmentData);
});
return responseData;
}
function createResponseDataProvider(id, provider_type, name, phone, mobile, email, logo, address) {
var responseData = {
id : id,
provider_type: provider_type,
name : name,
phone : phone,
mobile: mobile,
email: email,
logo: logo,
address : address
};
return responseData;
}
//=============get api/rovider/:id================
app.use("/", require('./lib/provider'));
require('./lib/provider');
module.exports.cloudant=cloudant;
module.exports.cloudant1="demo";
http.createServer(app).listen(app.get('port'), '0.0.0.0', function() {
console.log('Express server listening on port ' + app.get('port'));
});
and provider.js file
var router = require('express').Router();
var cloudant= require('../app').cloudant;
var cloudant1= require('../app').cloudant1;
//create del all whitespace of string function
String.prototype.delAllWhiteSpace = function() {
return this.split(' ').join('');
};
var Providers = {
getProvider: function(req, res){
console.log(cloudant);
console.log(cloudant1);
}
};
router.get('/abc/provider/', Providers.getProvider);
module.exports = exports = router;
when calling API http://demo.mybluemix.net/abc/provider, the return results are cloudant undefined

Express.js multilanguage with i18n-node

How to call controller with express.js routing?
app.get('*', function(req, res, next) {
var regExp = /^\/([a-z]{2})(\/|$)/gi,
exec = regExp.exec(req.url);
exec = exec != null ? exec[1] : undefined;
if(exec == undefined) {
// add language prefix to link
}
else {
i18n.setLocale(exec);
// add language prefix to link
}
next();
});
If I open the page /about I need to get url like this: http://example.com/en/about. How I can do it and how to display call 'about' controller?
app.get('/about', function(req, res) {
console.log('Here is about');
res.send('Hello, World');
});
Not suitable: app.get('(en|de|ru)/about', ...)
Thanks in advance.
You could do something like
app.get('/:language/about', function(req, res) {
var language = req.params.language;
i18n.setLocale(language);
});
For multiple routes you could maybe do this
controllers.js
module.exports = {
about: function(req, res) {
res.send('about');
}
}
app.js
var controllers = require('./controllers');
app.all('/:language/:controller', function(req, res) {
i18n.setLocale(req.params.language);
controllers[req.params.controller](req, res);
});
The following works for me very well, so the language code can be optional:
var i18n = require('i18n');
server.use(express.static(__dirname + '/client/www'));
server.use('/en', express.static(__dirname + '/client/www'));
server.use('/zh', express.static(__dirname + '/client/www'));
function regexPath(p) {
return new RegExp('(?:/(en|zh))?' + p, 'i');
}
server.use(i18n.init);
server.all('*', function (req, res, next) {
var l = /^\/(en|zh)/i;
if (l.test(req.url)) {
var a = l.exec(req.url);
var local = a[1];
i18n.setLocale(local);
res.setLocale(local);
} else {
i18n.setLocale('zh');
res.setLocale('zh');
}
next();
});
server.get(regexPath('/signin'), function (req, res) {
res.render('sign-in');
});

Expressjs - All Routes Are 404

In My Express App, for some reason, all of the routes are returning 404.
Server.js
/**
* Module dependencies
*/
var express = require('express')
var passport = require('passport')
var env = process.env.NODE_ENV || 'development'
var config = require('./config/config')[env]
var mongoose = require('mongoose')
var fs = require('fs')
require('./helpers')
require('express-namespace')
mongoose.connect(config.db)
// Bootstrap models
fs.readdirSync(__dirname + '/app/models').forEach(function (file) {
if (~file.indexOf('.js')) require(__dirname + '/app/models/' + file)
})
// Bootstrap passport config
require('./config/passport')(passport, config)
var app = express()
// Bootstrap application settings
require('./config/express')(app, config, passport)
// Bootstrap routes
require('./config/routes')(app, passport)
// Start the app by listening on <port>
var port = config.port || process.env.PORT || 3000
app.listen(port)
console.log('Express app started on port '+port)
// Expose app
module.exports = app
Routes.js
/**
* Module dependencies.
*/
var mongoose = require('mongoose')
var passportOptions = {
failureFlash: 'Invalid email or password.',
failureRedirect: '/login'
}
// controllers
var home = require('home')
var functions = require('function')
/**
* Expose
*/
module.exports = function (app, passport) {
console.log("SR");
app.get('/', function(req,res){
console.log("//////");
})
app.get('/functions/get',functions.get)
app.post('/functions/submit',functions.sub)
app.get('/login',passport.authenticate('google',{
"scope":"https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
"hd":"kinokiapp.com"
}))
app.get('/google/callback',passport.authenticate('google', { failureRedirect:"/" }),function(req,res){
res.end("auth")
})
console.log("ER");
}
Home.js
/*!
* Module dependencies.
*/
console.log("HIH");
exports.index = function (req, res) {
res.render('home', {
title: 'Node Express Mongoose Boilerplate'
})
}
function.js
var mongoose = require('mongoose')
var KIFunction = mongoose.model("KIFunction")
exports.get = function(req, res) {
res.type('text/kinoki-function')
res.status(200);
var exclude
try {
exclude = JSON.parse(req.query.n)
} catch (e) {
exclude = []
}
for (var i = 0; i < exclude.length; i++) {
if (typeof exclude[i] != 'string') {
continue;
}
exclude[i] = mongoose.Types.ObjectId(exclude[i])
}
KIFunction.random({
"_id":{
"$nin":exclude
},
approved1:true,
approved2:true,
}).limit(10).exec(function(err,functions){
if (err || functions.length == 0) {return res.end("false")}
var out = ''
functions.forEach(function(f){
out += "{0}#{1}#{2}#{3}|".format(f.steps, f.string, f.difficulty, f._id)
})
res.end(out.substring(0, out.length - 1),"utf8")
})
}
exports.sub = function(req,res){
var fstr = req.body.str
if (!(req.body.hasOwnProperty("str")) || !(fstr.match(KIFunction.functionRegex()))) {
res.status(400)
res.end("false")
return
}
new KIFunction({
string:fstr
}).save(function(err){
if(err) {
res.status(200)
return res.end("false")
}
res.status(200)
res.end("true")
})
}
the output is:
23 Aug 08:21:16 - [nodemon] starting node server.js HIH SR ER
Express app started on port 3000
GET / 404 571ms - 863b
config/config.js
/*!
* Module dependencies.
*/
var path = require('path')
var rootPath = path.resolve(__dirname + '../..')
/**
* Expose config
*/
module.exports = {
development: {
root: rootPath,
db: 'mongodb://localhost/kinoki_dev',
rootURL:"http://localhost/",
logger: 'dev'
},
test: {
root: rootPath,
db: 'mongodb://localhost/kinoki_test',
rootURL:"http://localhost/",
port: 9273,
logger: false
},
ci: {
root: rootPath,
db: ("mongodb://" + process.env.WERCKER_MONGODB_HOST + ":" + process.env.WERCKER_MONGODB_PORT + "/kinoki_ci"),
port: 2547,
rootURL:"http://localhost/",
logger: false
},
production: {
root: rootPath,
dbpass:"xyz",
db: 'mongodb://user:pass#mymongoserver.com:39768/kinoki',
rootURL:"http://kinokiapp.com/",
logger: 'dev'
}
}
config/express.js
/*!
* Module dependencies.
*/
var express = require('express')
var mongoStore = require('connect-mongo')(express)
var helpers = require('view-helpers')
var pkg = require('../package')
var flash = require('connect-flash')
var env = process.env.NODE_ENV || 'development'
var config = require("./config")[env]
/*!
* Expose
*/
module.exports = function (app, config, passport) {
// Add basic auth for staging
if (env === 'staging') {
app.use(express.basicAuth(function(user, pass){
return 'username' == user & 'password' == pass
}))
app.use(function (req, res, next) {
if (req.remoteUser && req.user && !req.user._id) {
delete req.user
}
next()
})
}
app.set('showStackError', true)
// use express favicon
app.use(express.favicon(config.root + '/public/favicon.ico'))
app.use(express.static(config.root + '/public'))
if(config.logger){
app.use(express.logger(config.logger))
}
// views config
app.set('views', config.root + '/app/views')
app.set('view engine', 'jade')
app.configure(function () {
// bodyParser should be above methodOverride
app.use(express.bodyParser())
app.use(express.methodOverride())
// cookieParser should be above session
app.use(express.cookieParser())
app.use(express.session({
secret: pkg.name,
store: new mongoStore({
url: config.db,
collection : 'sessions'
})
}))
// Passport session
app.use(passport.initialize())
app.use(passport.session())
// Flash messages
app.use(flash())
// expose pkg and node env to views
app.locals({
pkg:pkg,
env:env
})
// View helpers
app.use(helpers(pkg.name))
// routes should be at the last
app.use(app.router)
// custom error handler
app.use(function (err, req, res, next) {
if (err.message
&& (~err.message.indexOf('not found')
|| (~err.message.indexOf('Cast to ObjectId failed')))) {
return next()
}
console.error(err.stack)
res.status(500).render('500')
})
app.use(function (req, res, next) {
res.status(404).render('404', { url: req.originalUrl })
})
})
// development specific stuff
app.configure('development', function () {
app.locals.pretty = true;
})
// staging specific stuff
app.configure('staging', function () {
app.locals.pretty = true;
})
}
config/passport.js
/*!
* Module dependencies.
*/
var mongoose = require('mongoose')
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
var User = mongoose.model('User')
var config = require('./config')[process.env.NODE_ENV]
/**
* Expose
*/
module.exports = function(passport, config) {
// serialize sessions
passport.serializeUser(function(user, done) {
done(null, user.id)
})
passport.deserializeUser(function(id, done) {
User.findOne({
_id: id
}, function(err, user) {
done(err, user)
})
})
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: config.rootURL + 'google/callback'
},
function(accessToken, refreshToken, profile, done) {
User.findOne({
id: profile.id
}, function(err, user) {
if (err) {
return done(err)
}
if (!user) {
user = new User({
id: profile.id,
profile: profile,
accessToken:accessToken,
refreshToken:refreshToken
})
user.save(function(err) {
if (err) {
return done(err)
}
done(null, user)
})
} else {
done(null,user)
}
})
}
))
passport.reqAuth = function(req,res,next){
if(req.isAuthenticated())
return next()
else
res.redirect('/login')
}
}
config/routes.js
/**
* Module dependencies.
*/
var mongoose = require('mongoose')
var passportOptions = {
failureFlash: 'Invalid email or password.',
failureRedirect: '/login'
}
// controllers
var home = require('home')
var functions = require('function')
/**
* Expose
*/
module.exports = function (app, passport) {
console.log("SR");
app.get('/', function(req,res){
console.log("//////");
})
app.get('/functions/get',functions.get)
app.post('/functions/submit',functions.sub)
// app.get('/login',passport.authenticate('google',{
// "scope":"https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
// "hd":"kinokiapp.com"
// }))
// app.get('/google/callback',passport.authenticate('google', { failureRedirect:"/" }),function(req,res){
// res.end("auth")
// })
console.log("ER");
}
Does Anyone Know why all the routes are returning 404 (all of them are 404, i just don't have the logs).
Please let me know if you need more code.
Express 404's if a request gets to the end of the middleware chain without anything sending a response. So a common reason for this is a missing app.use(app.router).
In your case passport.deserializeUser(id, fn) throws an error within passport.session(). Express passes the request directly to your custom error handler, bypassing app.router. Since the error is not 'not found' it renders 404.
I would probably just return a user of null in the event that User.findOne(... doesn't find a user. You will need to make sure any templates that are shown to both logged-in and non-logged-in users handles both cases.
Also I use this often, it might come in handy:
function restrictToLoggedIn(req, res, next){
if(req.user && req.user !== null){
return next()
} else {
res.send(401, 'Must be logged in');
};
};
app.get('/'
, restrictToLoggedIn
, function(req, res, next){
// req.user is guranteed to be populated
res.locals.user = req.user;
res.render('home');
});
edit: leaving troubleshooting for posterity...
If app.use(app.router) already exists in your ./config/express, check the previous middlewares. You can set a single catchall route at the top of your routes.js to make sure that anything that hits the router sends 200: app.all('*', function(req,res){ res.send(200, req.originalUrl) });
Finally, confirm that require('function') is loading properly. I always use require('./function.js').
You can comment out your app.use(passport... middleware functions to test whether that's at fault.
If none of this helps please post your config/* javascript files.

Categories

Resources