grouping express routes into a single file - javascript

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)

Related

How to replace `require` function while upgrading a NodeJS project to TypeScript?

I am trying to modify an existing NodeJS project from JavaScript to TypeScript but I don't know how to deal with require expressions like below:
const indexRouter = require('../routes/index');
const config = require('./config');
EDIT: This is the index.ts dile:
import express, {Request, Response, NextFunction} from 'express';
const router = express.Router();
/* GET home page. */
router.get('/', function(req: Request, res: Response, next: NextFunction) {
res.render('index', { title: 'Express' });
});
export default router;
You don't have to change that lines. TypeScript understands CommonJS modules with the according configuration. But since you want to replace them, I assume you want to use ES6 modules.
It's
import indexRouter from '../routes/index';
import config from './config';

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

routing with express and es6 but got a TypeError

im using express and es6 and im trying to route in this way..
index.js
import express from 'express'
import bodyParser from 'body-parser'
import appRoutes from './routes/appRoutes.js'
var app = express();
app.use(express.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(express.json());
app.use('/api', appRoutes);
app.get('/', (req, res) => res.send("hellow express"));
app.listen(PORT, () => console.log(`Server runing on port : http://localhost:${PORT}`));
appRoutes.js
import express from 'express'
import {hello, sendMessage} from '../controllers/appController.js'
const appRoutes = express.Router();
appRoutes.get('/', hello);
appRoutes.post('/', sendMessage);
export default {appRoutes};
but run through this error.....
Router.use() requires a middleware function but got a Object
in appRoutes.js file, change this
export default {appRoutes};
into
export default appRoutes;
maybe you can try to redo importing and exporting in a similar way:
Only I think you don't need to pass and handle the db variable like I do

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.

Routes with a wrong format

I am working with Nodejs and I am trying to figure out why my routes are getting a wrong format, look at this example
I have a service named Dealers, and these are the routes
import express from 'express';
const router = new express.Router();
// POST METHODS
router.post('/create-dealer', require('./create-dealer'));
router.post('/update-dealer', require('./update-dealer'));
router.post('/deactive-dealer', require('./deactive-dealer'));
// GET METHODS
router.get('/get-dealers', require('./get-dealers'));
export default router;
and the general app.use
import { Router } from 'express';
const router = new Router();
router.use('/create-dealer', require('./dealers'));
router.use('/get-dealers', require('./dealers'));
router.use('/update-dealer', require('./dealers'));
router.use('/deactive-dealer', require('./dealers'));
export default router;
now, in order for me to work with this routes, I have to do for example in Postman
POST > http://localhost:8080/create-dealer/create-dealer
and why not only
POST > http://localhost:8080/create-dealer
what am I doing wrong?
In your app.js it should be:
import { Router } from 'express';
const router = new Router();
router.use(require('./dealers'));
export default router;
Because you already have the paths specified in dealers.js.
You're inserting that create-dealer segment twice by having it both in the .use file and again in the './dealers' file.
Either eliminate it where you use it:
router.use('/create-dealer', require('./dealers'));
to
router.use('/', require('./dealers'));
...which may mean you have to refactor './dealers' or you'll need to do the reverse, leave it with router.use and remove it in the dealers code.

Categories