How to call my middleware for all apis i have automatically? - javascript

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

Related

The requested module does not provide an export named default via express routing

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');

grouping express routes into a single file

I trying to express routes into a single file using app.use
app.js
import express from 'express'
import testRouter from 'testRouter'
const app = express()
app.use('/testRouter', testRouter)
app.listen(3000)
testRouter.js
import express from 'express'
const router = express.Router
router.get("/page1", function (req, res){
res.send("test")
})
export default router
using module exports is a official ways to do it and it worked
But why doesn't the router definition inside a function work like bellow?
app.js
import express from 'express'
import testRouter from 'testRouter'
const app = express()
app.use('/testRouter', function (){
const router = express.Router()
router.get("/page1", function (req, res){
res.send("test")
})
return router
}))
app.listen(3000)
I don't believe the code inside app.use('/test/Router', function() { }) executes until a user has visited your test/Router page at least once. I'm also not sure if you can use a middleware ("use") without having an eventual terminal endpoint.
Because in the official documentation testRouter is an Object
app.use('/testRouter', Object)
You put the function
app.use('/testRouter', Functon)

How to achieve DRY routers in express

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;

Express : router object and methods

I have
var router = express.Router();
router.get('/', function(req, res) {
//something
}
module.exports = router;
Is the router created, the get method executed and the router exported, or is it that the router is created, the method is define for this router (not executed) and the router is exported afterwards?
Second one. Router is created, method is defined and router is exported. That method will be executed when browser sends get request on '/' url, if you correctly require exported router.

Node.js router() usage confusion

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.

Categories