Routing


  • Plugin & Theme Dev

    Plug-in consists of:

    plugin.json:

    {
        "id": "nodebb-plugin-test",
        "name": "Plugin name",
        "url": "Path to Github",
        "library": "./index.js",
        "hooks": [
            {
                "hook": "filter:category.build"
                , "method": "reroute"
                , "callbacked": true
            }
        ]
    }
    

    index.js:

    (function(Preparsed) {
    'use strict';
    
    var async = module.parent.require('async'),
    	express = require('express'),
    	router = express.Router(),
    	middleware = require.main.require('./src/middleware'),
    	controllers = require.main.require('./src/controllers'),
    	helpers = require.main.require('./src/routes/helpers'),
    	setupPageRoute = helpers.setupPageRoute;
    
    
    Preparsed.reroute = function(data, callback){
    	setupPageRoute(router, '/category/category_id/:slug/:topic_index', middleware, [], controllers.categories.get);
    	setupPageRoute(router, '/category/category_id/:slug?', middleware, [middleware.addSlug], controllers.categories.get);
    	callback(null, data)
    }
    
    
    }(module.exports));
    

    package.json:

    {
      "name": "nodebb-plugin-test",
      "version": "1.0.0",
      "description": "Plugin description",
      "main": "index.js",
      "author": "me <me@mail.ru>",
      "license": "MIT",
      "dependencies": {
        "express": "^4.12.0",
        "passport-http-bearer": "^1.0.1"
      },
      "nbbpm": {
        "compatibility": "^0.6.0"
      }
    }
    
    

    But it not work, while displaying an error:

    16/3 17:52 [13852] - error: Error: Route.get() requires callback functions but got a [object Undefined]
        at Route.<anonymous> (/home/me/nodebb/node_modules/nodebb-plugin-test/node_modules/express/lib/router/route.js:170:15)
        at Array.forEach (native)
        at Route.(anonymous function) [as get] (/home/me/nodebb/node_modules/nodebb-plugin-test/node_modules/express/lib/router/route.js:166:15)
        at Function.proto.(anonymous function) [as get] (/home/me/nodebb/node_modules/nodebb-plugin-test/node_modules/express/lib/router/index.js:498:19)
        at helpers.setupPageRoute (/home/me/nodebb/src/routes/helpers.js:8:9)
        at Object.Preparsed.reroute [as method] (/home/me/nodebb/node_modules/nodebb-plugin-test/index.js:14:2)
        at /home/me/nodebb/src/plugins/hooks.js:89:12
        at /home/me/nodebb/node_modules/async/lib/async.js:272:13
        at iterate (/home/me/nodebb/node_modules/async/lib/async.js:149:13)
        at Object.async.eachSeries (/home/me/nodebb/node_modules/async/lib/async.js:165:9)
    Error: Route.get() requires callback functions but got a [object Undefined]
        at Route.<anonymous> (/home/me/nodebb/node_modules/nodebb-plugin-test/node_modules/express/lib/router/route.js:170:15)
        at Array.forEach (native)
        at Route.(anonymous function) [as get] (/home/me/nodebb/node_modules/nodebb-plugin-test/node_modules/express/lib/router/route.js:166:15)
        at Function.proto.(anonymous function) [as get] (/home/me/nodebb/node_modules/nodebb-plugin-test/node_modules/express/lib/router/index.js:498:19)
        at helpers.setupPageRoute (/home/me/nodebb/src/routes/helpers.js:8:9)
        at Object.Preparsed.reroute [as method] (/home/me/nodebb/node_modules/nodebb-plugin-test/index.js:14:2)
        at /home/me/nodebb/src/plugins/hooks.js:89:12
        at /home/me/nodebb/node_modules/async/lib/async.js:272:13
        at iterate (/home/me/nodebb/node_modules/async/lib/async.js:149:13)
        at Object.async.eachSeries (/home/me/nodebb/node_modules/async/lib/async.js:165:9)
    

    The challenge is to replace route category/id/categoryname on categoryname.


  • Plugin & Theme Dev

    In file src/routes/index.js in categoryRoutes(router, middleware, controllers); uses function middleware, which is defined as the file src/webserver.js, how: middleware = middleware(app);
    What is the app?


  • Plugin & Theme Dev

    I come from the world of php, in which i little worked with js and jquery, help out me! ) Please


  • Plugin & Theme Dev

    Expel me from the world of PHP)


  • Global Moderator

    Use the plugin static:init hook. It gives the router, app, and middleware objects.


  • Plugin & Theme Dev

    @pitaj How do I know that can be obtained using the hook? console.log(data) not work. And i try to find static:init in google, but it is impossible.


  • Plugin & Theme Dev

    @pitaj said:

    Use the plugin static:init hook. It gives the router, app, and middleware objects.

    Can i see an exemple? Maybe it - https://github.com/psychobunny/nodebb-plugin-custom-pages/blob/26cec978f13da185163a59a5f4db67450cafbe1f/library.js#L96


  • Plugin & Theme Dev

    I commented string //categoryRoutes(router, middleware, controllers); in src/routes/index.js file and add all of this file in index.js my plugin:

    (function(Preparsed) {
    'use strict';
    
    var nconf = module.parent.require('nconf'),
    	path = module.parent.require('path'),
    	winston = module.parent.require('winston'),
    	controllers = require.main.require('./src/controllers'),
    	meta = require.main.require('./src/meta'),
    	plugins = require.main.require('./src/plugins'),
    	express = module.parent.require('express'),
    
    	metaRoutes = require.main.require('./src/routes/meta'),
    	apiRoutes = require.main.require('./src/routes/api'),
    	adminRoutes = require.main.require('./src/routes/admin'),
    	feedRoutes = require.main.require('./src/routes/feeds'),
    	pluginRoutes = require.main.require('./src/routes/plugins'),
    	authRoutes = require.main.require('./src/routes/authentication'),
    	helpers = require.main.require('./src/routes/helpers');
    	
    var setupPageRoute = helpers.setupPageRoute;
    
    
    function mainRoutes(app, middleware, controllers) {
    	setupPageRoute(app, '/', middleware, [], controllers.home);
    
    	var loginRegisterMiddleware = [middleware.redirectToAccountIfLoggedIn];
    
    	setupPageRoute(app, '/login', middleware, loginRegisterMiddleware, controllers.login);
    	setupPageRoute(app, '/register', middleware, loginRegisterMiddleware, controllers.register);
    	setupPageRoute(app, '/confirm/:code', middleware, [], controllers.confirmEmail);
    	setupPageRoute(app, '/outgoing', middleware, [], controllers.outgoing);
    	setupPageRoute(app, '/search/:term?', middleware, [middleware.guestSearchingAllowed], controllers.search.search);
    	setupPageRoute(app, '/reset/:code?', middleware, [], controllers.reset);
    	setupPageRoute(app, '/tos', middleware, [], controllers.termsOfUse);
    }
    
    function staticRoutes(app, middleware, controllers) {
    	setupPageRoute(app, '/404', middleware, [], controllers.static['404']);
    	setupPageRoute(app, '/403', middleware, [], controllers.static['403']);
    	setupPageRoute(app, '/500', middleware, [], controllers.static['500']);
    }
    
    function topicRoutes(app, middleware, controllers) {
    	app.get('/api/topic/teaser/:topic_id', controllers.topics.teaser);
    
    	setupPageRoute(app, '/topic/:topic_id/:slug/:post_index?', middleware, [], controllers.topics.get);
    	setupPageRoute(app, '/topic/:topic_id/:slug?', middleware, [middleware.addSlug], controllers.topics.get);
    }
    
    function tagRoutes(app, middleware, controllers) {
    	setupPageRoute(app, '/tags/:tag', middleware, [middleware.publicTagListing], controllers.tags.getTag);
    	setupPageRoute(app, '/tags', middleware, [middleware.publicTagListing], controllers.tags.getTags);
    }
    
    function categoryRoutes(app, middleware, controllers) {
    	setupPageRoute(app, '/categories', middleware, [], controllers.categories.list);
    	setupPageRoute(app, '/popular/:term?', middleware, [], controllers.categories.popular);
    	setupPageRoute(app, '/recent', middleware, [], controllers.categories.recent);
    	setupPageRoute(app, '/unread', middleware, [middleware.authenticate], controllers.categories.unread);
    	app.get('/api/unread/total', middleware.authenticate, controllers.categories.unreadTotal);
    
    	setupPageRoute(app, '/category/:category_id/:slug/:topic_index', middleware, [], controllers.categories.get);
    	setupPageRoute(app, '/category/:category_id/:slug?', middleware, [middleware.addSlug], controllers.categories.get);
    }
    
    function accountRoutes(app, middleware, controllers) {
    	var middlewares = [middleware.checkGlobalPrivacySettings];
    	var accountMiddlewares = [middleware.checkGlobalPrivacySettings, middleware.checkAccountPermissions];
    
    	setupPageRoute(app, '/user/:userslug', middleware, middlewares, controllers.accounts.getAccount);
    	setupPageRoute(app, '/user/:userslug/following', middleware, middlewares, controllers.accounts.getFollowing);
    	setupPageRoute(app, '/user/:userslug/followers', middleware, middlewares, controllers.accounts.getFollowers);
    	setupPageRoute(app, '/user/:userslug/posts', middleware, middlewares, controllers.accounts.getPosts);
    	setupPageRoute(app, '/user/:userslug/topics', middleware, middlewares, controllers.accounts.getTopics);
    	setupPageRoute(app, '/user/:userslug/groups', middleware, middlewares, controllers.accounts.getGroups);
    
    	setupPageRoute(app, '/user/:userslug/favourites', middleware, accountMiddlewares, controllers.accounts.getFavourites);
    	setupPageRoute(app, '/user/:userslug/watched', middleware, accountMiddlewares, controllers.accounts.getWatchedTopics);
    	setupPageRoute(app, '/user/:userslug/edit', middleware, accountMiddlewares, controllers.accounts.accountEdit);
    	setupPageRoute(app, '/user/:userslug/settings', middleware, accountMiddlewares, controllers.accounts.accountSettings);
    
    	setupPageRoute(app, '/notifications', middleware, [middleware.authenticate], controllers.accounts.getNotifications);
    	setupPageRoute(app, '/chats/:userslug?', middleware, [middleware.redirectToLoginIfGuest], controllers.accounts.getChats);
    }
    
    function userRoutes(app, middleware, controllers) {
    	var middlewares = [middleware.checkGlobalPrivacySettings];
    
    	setupPageRoute(app, '/users', middleware, middlewares, controllers.users.getOnlineUsers);
    	setupPageRoute(app, '/users/online', middleware, middlewares, controllers.users.getOnlineUsers);
    	setupPageRoute(app, '/users/sort-posts', middleware, middlewares, controllers.users.getUsersSortedByPosts);
    	setupPageRoute(app, '/users/sort-reputation', middleware, middlewares, controllers.users.getUsersSortedByReputation);
    	setupPageRoute(app, '/users/latest', middleware, middlewares, controllers.users.getUsersSortedByJoinDate);
    	setupPageRoute(app, '/users/search', middleware, middlewares, controllers.users.getUsersForSearch);
     }
    
    function groupRoutes(app, middleware, controllers) {
    	var middlewares = [middleware.checkGlobalPrivacySettings, middleware.exposeGroupName];
    
    	setupPageRoute(app, '/groups', middleware, middlewares, controllers.groups.list);
    	setupPageRoute(app, '/groups/:slug', middleware, middlewares, controllers.groups.details);
    	setupPageRoute(app, '/groups/:slug/members', middleware, middlewares, controllers.groups.members);
    }
    
    
    Preparsed.init = function(params, callback){
    	var app = params.router,
    		middleware = params.middleware,
    		controllers = params.controllers;
    		
    	var router = express.Router(),
    		pluginRouter = express.Router(),
    		authRouter = express.Router(),
    		relativePath = nconf.get('relative_path');
    
    	pluginRouter.render = function() {
    		app.render.apply(app, arguments);
    	};
    
    	// Set-up for hotswapping (when NodeBB reloads)
    	pluginRouter.hotswapId = 'plugins';
    	authRouter.hotswapId = 'auth';
    
    	app.use(middleware.maintenanceMode);
    
    	app.all(relativePath + '/api/?*', middleware.prepareAPI);
    	app.all(relativePath + '/api/admin/?*', middleware.isAdmin);
    	app.all(relativePath + '/admin/?*', middleware.ensureLoggedIn, middleware.applyCSRF, middleware.isAdmin);
    
    	adminRoutes(router, middleware, controllers);
    	metaRoutes(router, middleware, controllers);
    	apiRoutes(router, middleware, controllers);
    	feedRoutes(router, middleware, controllers);
    	pluginRoutes(router, middleware, controllers);
    
    	/**
    	* Every view has an associated API route.
    	*
    	*/
    
    	mainRoutes(router, middleware, controllers);
    	staticRoutes(router, middleware, controllers);
    	topicRoutes(router, middleware, controllers);
    	tagRoutes(router, middleware, controllers);
    	categoryRoutes(router, middleware, controllers);
    	accountRoutes(router, middleware, controllers);
    	userRoutes(router, middleware, controllers);
    	groupRoutes(router, middleware, controllers);
    
    	app.use(relativePath, pluginRouter);
    	app.use(relativePath, router);
    	app.use(relativePath, authRouter);
    
    	if (process.env.NODE_ENV === 'development') {
    		require('./debug')(app, middleware, controllers);
    	}
    
    	app.use(function(req, res, next) {
    		if (req.user || parseInt(meta.config.privateUploads, 10) !== 1) {
    			return next();
    		}
    		if (req.path.indexOf('/uploads/files') === 0) {
    			return res.status(403).json('not-allowed');
    		}
    		next();
    	});
    
    	app.use(relativePath, express.static(path.join(__dirname, '../../', 'public'), {
    		maxAge: app.enabled('cache') ? 5184000000 : 0
    	}));
    
    	handle404(app, middleware);
    	handleErrors(app, middleware);
    
    
    	// Add plugin routes
    	plugins.init(app, middleware);
    	authRoutes.reloadRoutes();
    	
    	callback();
    	
    };
    
    function handle404(app, middleware) {
    	app.use(function(req, res, next) {
    		if (plugins.hasListeners('action:meta.override404')) {
    			return plugins.fireHook('action:meta.override404', {
    				req: req,
    				res: res,
    				error: {}
    			});
    		}
    
    		var relativePath = nconf.get('relative_path');
    		var	isLanguage = new RegExp('^' + relativePath + '/language/[\\w]{2,}/.*.json'),
    			isClientScript = new RegExp('^' + relativePath + '\\/src\\/.+\\.js');
    
    		if (isClientScript.test(req.url)) {
    			res.type('text/javascript').status(200).send('');
    		} else if (isLanguage.test(req.url)) {
    			res.status(200).json({});
    		} else if (req.accepts('html')) {
    			if (process.env.NODE_ENV === 'development') {
    				winston.warn('Route requested but not found: ' + req.url);
    			}
    
    			res.status(404);
    
    			if (res.locals.isAPI) {
    				return res.json({path: req.path, error: 'not-found'});
    			}
    
    			middleware.buildHeader(req, res, function() {
    				res.render('404', {path: req.path});
    			});
    		} else {
    			res.status(404).type('txt').send('Not found');
    		}
    	});
    }
    
    function handleErrors(app, middleware) {
    	app.use(function(err, req, res, next) {
    		if (err.code === 'EBADCSRFTOKEN') {
    			winston.error(req.path + '\n', err.message)
    			return res.sendStatus(403);
    		}
    
    		winston.error(req.path + '\n', err.stack);
    
    		if (parseInt(err.status, 10) === 302 && err.path) {
    			return res.locals.isAPI ? res.status(302).json(err.path) : res.redirect(err.path);
    		}
    
    		res.status(err.status || 500);
    
    		if (res.locals.isAPI) {
    			return res.json({path: req.path, error: err.message});
    		} else {
    			middleware.buildHeader(req, res, function() {
    				res.render('500', {path: req.path, error: err.message});
    			});
    		}
    	});
    }
    
    
    }(module.exports));
    

    Changing accordingly all paths and replaced var app, middleware and controllers. But not work:
    Снимок экрана от 2015-03-17 00:30:46.png
    Tried on action:app.load and action:init.


 

| |