What i'm trying to do:
If the url exists in the db use static page template, if not, display specific page template. Can't seem to figure out, how too...
My app.js file
app.get('*', function(req, res){
var currenturl = req.url;
console.log('URL IS: ' + my_path)
if (!!db.get(my_path) )
{
//If it does exist in db
console.log('Does exist');
res.render('index', { thetitle: 'Express', title: db.get(currenturl).title, content: db.get(currenturl).content });
}else{
//If it doesn't exist in db
redirect to other sites
Like:
if you go to "/page" it will run this => app.get('/page', routes.index)
or "/users" will run => app.get('/users', routes.users)
}
});
You have to create your own simple middleware. Just make sure you put it above the express.router
app.use(function(req, res, next){
if (!!db.get(my_path)) {
// render your site from db
} else {
// call next() to continue with your normal routes
next();
}
});
app.get('/existsInDB', function(req, res) {
// should be intercepted by the middleware
})
app.get('/page', function(req, res) {
// should not be intercepted
res.render('page')
})
using express is easy. you can use the redirect function:
if (url_exists) res.render('index');
else res.redirect('/foo/bar');
Related
I am trying to implement user redirection with Passport on NodeJS and Express Backend script. The issue that I am facing is that my login page is not my default home page but it's rather this:
localhost:3000/login
I've managed to make it so that if user is not registered, he cannot access other pages such as /index or /dashboard but something breaks when I try to access hard-coded urls such as:
If I enter localhost:3000/ I can gain access to the default index.html page even if I'm not logged in. Just to clarify - localhost:3000/index == localhost:3000.
If I decide to manipulate the route like this: localhost:3000/Example/pages/index.html or localhost:3000/Example/pages/dashboard.html it would allow me to access the pages even if I am logged in.
My question is, how can I restrict users to manipulate the route to the default homepage and any other pages which have not been declared in the Node Backend?
My Node Routes Code:
app.get('/login',
function(req, res){
res.sendFile(path.join(__dirname + '/login.html'));
});
app.get('/index', isLoggedIn,
function(req, res){
res.sendFile(path.join(__dirname + '/index.html'));
});
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/index');
});
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/index');
});
I've tried using this:
app.use(function(req, res, next) {
if (req.session.user == undefined) {
return res.render('/login', { failureRedirect:'/login' });
}
else {
next();
}
});
but I receive an error: No default engine was specified and no extension was provided. I don't want to use JADE or Handlebars or anything else as an engine, just static HTML.
How can I restrict the route manipulation without having to define the rest of my node pages as app.get(/something, function(req,res){});
You can make a passport middleware to check if the user is authenticated
isAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
};
And then you can do this
app.get('/someroute', isAuthenticated, (req, res)=>{
// do what you want
});
I have the following code as a schema module:
router.get('/', function(req, res) {
Module.find(function (err, modules) {
if (!err) {
return res.json(modules);
} else {
res.statusCode = 500;
log.error('Internal error(%d): %s', res.statusCode, err.message);
return res.json({
error: 'Server error'
});
}
});
});
And this works fine for my API, but I'm also trying to use this data to load it into my Jade template.
var modules = require('./routes/modules');
// home page
app.get('/', function(req, res) {
res.render('index', { modules: modules })
});
app.use('/api/modules', modules);
But this just doesn't work, it gives me undefined as if it doesn't exist (when logged).
If I modify my router to the following:
res.render('index', {
modules: modules
})
It works fine for getting the data but not when accessing it through my API.
So my question, how can I use this particular piece of code for my API and for rendering it to the Jade template.
Your use of modules as the middleware is not correct. i.e.
app.use('/api/modules', modules);
As specified in the http://expressjs.com/en/guide/using-middleware.html, your middleware should call the next() function.
app.use(function (req, res, next) {
console.log('Time:', Date.now());
next();
});
To solve this, you should define your route similar to the index route, but you will use res.send.
var modules = require('./routes/modules');
// home page
app.get('/', function(req, res) {
res.render('index', { modules: modules })
});
app.get('/api/modules', function(req, res) {
res.send({ modules: modules })
});
I have the following function that I placed inside a separate js file.
I am trying to use it inside another javascript file that requires passport.js, and I would like to call it using app.use to further modularize my application
var express = require('express');
var router = express.Router();
/* GET welcome page. */
router.get('/home', isLoggedIn, function(req, res, next) {
res.render('home', {
title: 'title',
user : req.user
});
});
// route middleware to make sure
function isLoggedIn(req, res, next) {
// if user is authenticated in the session
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
module.exports = router;
The reason I created it is so I reduce redundancy and not use the following code each time:
app.get('/home', isLoggedIn, function(req, res) {
res.render('home.ejs', {
user : req.user // get the user out of session and pass to template
});
});
However I can't seem to get it to work. is authenticated is undefined although it is in the same folder, and it gives me an error 404 not found when I issue a get. How I can keep it in an external file and still use it? should I also pass it the user argument from where I am calling it?
var express = require('express');
var router = express.Router();
module.exports = function (app, passport){
router.get('/home', isLoggedIn, function(req, res, next) {
res.render('home', {
title: 'title',
user : req.user
});
});
return router;
};
function isLoggedIn(req, res, next) {
// if user is logged in -
if (req.isAuthenticated())
return next();
// if they aren't redirect them to home
res.redirect('/');
}
I have just started learning MEAN stack and going through tutorial in which I have files, api.js and auth.js.
In api.js I have below route structure,
var express = require('express');
var router = express.Router();
//Used for routes that must be authenticated.
function isAuthenticated (req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects
//allow all get request methods
if(req.method === "GET"){
console.log('in console');
return next();
}
if (req.isAuthenticated()){
return next();
}
// if the user is not authenticated then redirect him to the login page
return res.redirect('/#login');
};
//Register the authentication middleware
router.use('/posts', isAuthenticated);
router.route('/posts')
.get(function(req,res){
res.send({message:'TODO: return all posts'});
})
.post(function(req,res){
res.send({message:'TODO: create new post'});
});
router.route('/posts/:id')
.get(function(req,res){
res.send({message:'TODO: return post with ID ' + req.params.id});
})
.put(function(req,res){
res.send({message:'TODO: modify post with ID ' + req.params.id});
})
.delete(function(req,res){
res.send({message:'TODO: delete post with ID ' + req.params.id});
});
module.exports = router;
In auth.js I have below route structure,
var express = require('express');
var router = express.Router();
module.exports = function(passport){
//sends successful login state back to angular
router.get('/success', function(req, res){
res.send({state: 'success', user: req.user ? req.user : null});
});
//sends failure login state back to angular
router.get('/failure', function(req, res){
res.send({state: 'failure', user: null, message: "Invalid username or password"});
});
//log in
router.post('/login', passport.authenticate('login', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
//sign up
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
//log out
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
}
Above code works fine but whenever I try to rewrite code of api.js like auth.js structure below,
module.exports = function(){
router.get('/posts',function(req,res)
{
res.send({message:'TODO: return all posts'});
});
router.post('/posts',function(req,res)
{
res.send({message:'TODO: add new post'});
});
router.get('/posts/:id',function(req,res)
{
res.send({message:'TODO: return post with ID ' + req.params.id});
});
router.put('/posts/:id',function(req,res)
{
res.send({message:'TODO: edit post with ID ' + req.params.id});
});
router.delete('/posts/:id',function(req,res)
{
res.send({message:'TODO: delete post with ID ' + req.params.id});
});
return router;
}
This doesn't work. Below is the screen shot of the node cmd prompt whenever I make any post or get request. Am I rewriting code in wrong manner ?
You're exporting a function vs. a Router instance in api.js now. If you didn't change the file that uses api.js accordingly, you will be mounting a function instead of a Router.
So for the new api.js, your parent file will need to be doing something like:
var apiRoutes = require('./api')();
app.use('/api', apiRoutes);
instead of something like:
var apiRoutes = require('./api');
app.use('/api', apiRoutes);
I'm trying to build a server that user will be able to enter these valid paths:
/art/thisProject
/art/thatProject
and in case the user enters anything else invalid such as these the user will be redirected to root and then to the default path /art/myProject:
/some/url
/something
/another/u/rl
I guess the error comes because of a false use of "*"or with false understanding of how to override router rules.
How do I do it?
this is my code:
app.get('/', function(req, res) {
res.redirect('/art/myProject')
});
app.get('/art/:project', function(req, res){
var project = req.param('project');
var filePath = 'art/' + project + '/' + project;
res.render(filePath)
});
app.get('*', function(req, res) {
res.redirect('/')
});
This should work:
app.get('/*', function(req, res) {
res.redirect('/')
});
Or this:
app.use(function(req, res) {
res.redirect('/')
});
Both must of course be put last.