I am building a webapp in the form of a network of sorts with basic CRUD actions. I am in the process of splitting up my router files as they are becoming rather large.
I have an 'actions' route which does things such as selecting an in individual post to view, voting on a post, viewing a profile and commending a user. I cannot seem to find a way to allow me to split these 'action' routes into a seperate file and then use them as needed in the main route.
//index.js file in routes folder
var express = require('express');
var router = express.Router();
//main route
router.route('/feed')
.get(function(req, res, next){
//some code here
}
//actions.js file in routes folder
var express = require('express');
var router = express.Router();
//vote route
router.route('/vote/:id')
.post(function(req, res, next){
//some code here
}
//item route
router.route('/item/:id')
.get(function(req, res, next){
//some code here
}
I'd like to be able to use the action routes inside of the feed routes (and other routes) So I can do things like
POST /feed/vote/postid12356
GET /feed/item/itemid123456
or even in another route called 'private-feed' using the same actions from the actions route
POST /private-feed/vote/postid12356
GET /private-feed/item/itemid123456
Without having to have these actions repeated in many routes.
Is there any way in express that this can be done?
You can extract your route handler into a separate file, let's call them controllers and then reuse the logic in some of the routes:
//controllers/action.js
module.exports = {
get: (req, res, next) => {
//your post logic
}
}
///routes/item.js
const ActionController = require("../controllers/action");
router.route('/item/:id').get(ActionController.get);
module.exports = router;
Related
I'm in the need of assistance on finding what exactly i'm missing here.
If it helps, my app is on node.js (16.13.1) using the latest version of express as well as a nginx reverse proxy.
app.mjs
import router from './assets/js/router.mjs'; //Imports our routes
import express from 'express';
const expressapp = express(); //Creates the application with express
const moduleURL = new URL(import.meta.url); //Creates a new URL to use for the current directory name
const __dirname = path.dirname(moduleURL.pathname); //Creates the directory name and attaches it to the __dirname constant.
//Middleware
//Instructions for the app to use body parser & JSON goes here
expressapp.use('/subscribe', router); //Use the subscribe route
expressapp.use(express.static(__dirname, {index: 'index.html'})); //Tells the app to use the current path, with the index being index.html
expressapp.post('/subscribe', (req, res) =>
{
//post request stuff goes here
}
router.mjs
import express from 'express';
var router = express.Router();
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Gaming Galaxy Landing Page')
})
// define the subscribe route
router.get('/subscribe', function (req, res) {
res.send('Subscribe route')
})
export default router;
Error
import router from './assets/js/router.mjs'; //Imports our routes
^^^^^^
SyntaxError: The requested module './assets/js/router.mjs' does not provide an export named 'default'
at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:181:5)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
at async loadESM (node:internal/process/esm_loader:88:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
As someone who's somewhat new to this stuff, I really don't know what's wrong when I specifically defined a default export in my router. If anyone could help me learn what exactly is going on here it'll be very much appreciated
I think u have forgotten to save router.mjs file as I did the same mistake and got this error :)
try this code
const express = require('express');
I want my routes to be like the following:
/
/business
/business/stuff1
/business/stuff2
/business/admin
for /business I want to have a separate file for the routing and functions.
and also for /business/admin I want to have a separate file for the routing and functions.
so what I did is:
app.js
//Business route
const business = require("./business/business");
app.use("/business", business);
This works fine - but when I add in business.js
//admin route
const admin = require("./admin");
app.use("/admin", admin);
I get 404 for some reason.
Depends on what you are exporing from business.js. It should be an instance of express.Router and you have to mount the /admin route on this instance. Example:
// business.js
const admin = require("./admin");
const businessApp = express.Router();
businessApp.use("/admin", admin);
module.exports = businessApp;
I created a service in express to send emails, now I'm implementing a middleware for jwt authentication, it is already working, now I would like this middleware to be called automatically for any api I have or the ones I will cre
I tried to do the following assignment on my root, checkToken is my function on middleware
const app = express();
app.use(checkToken, require('./middlewares'))
app.use(`${config.URL_BASE}/email`, require('./apis/email'))
.
.
.
currently to call the middleware i'm doing, its works very well
router.post('', middleware.checkToken, async function (req, res) {
const {
type: typeCode,
.
.
.
its works very well, but my other api dont call the middleware, i didn't want to explicitly call again
Other api
router.get('/health', async (req, res) => {
res.status(200).send({ message: 'Ready.' })
})
To have middleware called for all routes, just do an app.use(yourMiddleware) before any of the routes are defined.
To have middleware called for one set of routes, but not other routes, put all the routes you want the middleware to be called for on a particular router that has a path prefix that only matches a subset of your routes. Then execute the middleware on that router before any of its routes are defined.
Here's an example of the 2nd option:
const express = require('express');
const app = express();
// load and configure api router
app.use('/api', require('./apiRouter.js'));
app.listen(...);
Then, inside apiRouter.js:
const router = require('express').Router();
// middleware that is called for all api routes
router.use(myMiddleware);
// define api routes here
router.get('/list', ...)
module.exports = router;
router.use() mounts middleware for the routes served by the specific router.
router.use(checkToken)
router.get('/health', getHandler)
router.post('/', postHandler)
module.exports = router
why we need to use for example var route = Router(); since by default below simple example of express already fullful the usage of route :
var express = require('express'),
app = express();
app.get('/login',function(req,res,next){
//..something
});
The express.Router class can be used to create modular mountable route handlers. A Router instance is a complete middleware and routing system; for this reason it is often referred to as a “mini-app”.
The following example creates a router as a module, loads a middleware in it, defines some routes, and mounts it on a path on the main app.
Create a router file named birds.js in the app directory, with the following content:
var express = require('express');
var router = express.Router();
// middleware specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// define the home page route
router.get('/', function(req, res) {
res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
res.send('About birds');
});
module.exports = router;
Then, load the router module in the app:
var birds = require('./birds');
...
app.use('/birds', birds);
The app will now be able to handle requests to /birds and /birds/about, along with calling the timeLog middleware specific to the route.
I'm using node, express and connect for a simple app and have basic HTTP auth implemented as follows (lots of code left out for brevity):
var express = require('express'),
connect = require('connect');
app.configure = function(){
// other stuff...
app.use(connect.basicAuth('username', 'password'));
// other stuff...
};
I've tried googling and even attempted implementing my own auth, but I can't figure out how to skip this auth for just one route.
I'd really appreciate it if anyone offer any help with this?
If you don't want to use authentication for all routes, you should add the auth function as middleware to each individual route like so:
app.get('/mysecretpage', basicAuth, function (req, res) {
console.log('you have to be auth to see this page');
});
Here is a regular route without auth:
app.get('/sample', function (req, res) {
console.log('everybody see this page');
});
This link may be useful for you also: how to implement login auth in node.js