admin管理员组

文章数量:1345475

Gadget Controller Ts Code :

import { Request, Response, NextFunction } from 'express';
import { Status } from '@prisma/client'
import prisma from '../utils/prisma.client';
import { AppError } from '../utils/error.handler';

// Generate random codename for gadgets
const generateCodename = (): string => {
  const adjectives = ['Mighty', 'Silent', 'Phantom', 'Shadow', 'Stealth', 'Covert', 'Invisible', 'Deadly', 'Rapid', 'Quantum'];
  const nouns = ['Eagle', 'Panther', 'Cobra', 'Viper', 'Falcon', 'Wolf', 'Hawk', 'Tiger', 'Raven', 'Phoenix'];
  
  const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];
  const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];
  
  return `The ${randomAdjective} ${randomNoun}`;
};

// Generate random mission success probability
const generateMissionProbability = (): number => {
  return Math.floor(Math.random() * 100);
};

// Get all gadgets with optional status filter
export const getAllGadgets = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { status } = req.query;
    
    const whereClause = status ? { status: status as Status } : {};
    
    const gadgets = await prisma.gadget.findMany({
      where: whereClause
    });
    
    const gadgetsWithProbability = gadgets.map(gadget => ({
      ...gadget,
      missionSuccessProbability: generateMissionProbability()
    }));
    
    res.status(200).json({
      status: 'success',
      results: gadgetsWithProbability.length,
      data: {
        gadgets: gadgetsWithProbability
      }
    });
  } catch (error) {
    next(error);
  }
};

// Create a new gadget
export const createGadget = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { status } = req.body;
    
    const gadget = await prisma.gadget.create({
      data: {
        name: generateCodename(),
        status: status || 'Available'
      }
    });
    
    res.status(201).json({
      status: 'success',
      data: {
        gadget
      }
    });
  } catch (error) {
    next(error);
  }
};

// Update a gadget
export const updateGadget = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params;
    const { name, status } = req.body;
    
    const gadget = await prisma.gadget.findUnique({
      where: { id }
    });
    
    if (!gadget) {
      return next(new AppError('No gadget found with that ID', 404));
    }
    
    const updatedGadget = await prisma.gadget.update({
      where: { id },
      data: {
        name,
        status
      }
    });
    
    res.status(200).json({
      status: 'success',
      data: {
        gadget: updatedGadget
      }
    });
  } catch (error) {
    next(error);
  }
};

// Decommission a gadget (soft delete)
export const decommissionGadget = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params;
    
    const gadget = await prisma.gadget.findUnique({
      where: { id }
    });
    
    if (!gadget) {
      return next(new AppError('No gadget found with that ID', 404));
    }
    
    const decommissionedGadget = await prisma.gadget.update({
      where: { id },
      data: {
        status: 'Decommissioned',
        decomissionedAt: new Date()
      }
    });
    
    res.status(200).json({
      status: 'success',
      data: {
        gadget: decommissionedGadget
      }
    });
  } catch (error) {
    next(error);
  }
};

// Trigger self-destruct sequence for a gadget
export const selfDestructGadget = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params;
    
    const gadget = await prisma.gadget.findUnique({
      where: { id }
    });
    
    if (!gadget) {
      return next(new AppError('No gadget found with that ID', 404));
    }
    
    // Generate confirmation code
    const confirmationCode = Math.floor(100000 + Math.random() * 900000);
    
    const updatedGadget = await prisma.gadget.update({
      where: { id },
      data: {
        status: 'Destroyed',
        selfDestruct: new Date()
      }
    });
    
    res.status(200).json({
      status: 'success',
      confirmationCode,
      message: 'Self-destruct sequence initiated',
      data: {
        gadget: updatedGadget
      }
    });
  } catch (error) {
    next(error);
  }
};

The Gadgets Routes : 
router.get('/', getAllGadgets);
router.post('/', createGadget);
router.patch('/:id', updateGadget);
router.delete('/:id', decommissionGadget);
router.post('/:id/self-destruct', selfDestructGadget);

Even though i have no error in the routing , still i am getting the error :
throw new TypeError(Missing parameter name at ${i}: ${DEBUG_URL}); ^ TypeError: Missing parameter name at 1: /pathToRegexpError

I possibly tried everything , GPT , V0 , StackOverFlow but the solutions didn't work.

Here is the package.json :

{
  "name": "pg_imp",
  "version": "1.0.0",
  "main": "dist/index.js",
  "scripts": {
    "start": "node dist/index.js",
    "dev": "ts-node-dev --respawn --transpile-only src/index.ts",
    "build": "tsc",
    "prisma:generate": "prisma generate",
    "prisma:migrate": "prisma migrate dev --name init"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "devDependencies": {
    "@types/bcrypt": "^5.0.2",
    "@types/cors": "^2.8.17",
    "@types/express": "^5.0.1",
    "@types/jsonwebtoken": "^9.0.9",
    "@types/uuid": "^10.0.0",
    "prisma": "^6.5.0",
    "ts-node-dev": "^2.0.0",
    "typescript": "^5.8.2"
  },
  "dependencies": {
    "@prisma/client": "^6.5.0",
    "bcrypt": "^5.1.1",
    "cors": "^2.8.5",
    "dotenv": "^16.4.7",
    "express": "^5.1.0",
    "express-validator": "^7.2.1",
    "helmet": "^8.1.0",
    "jsonwebtoken": "^9.0.2",
    "pg": "^8.14.1",
    "uuid": "^11.1.0"
  }
}


Can somebody please tell , how to fix the bug ! i am unable to fix this since 48Hrs (Skill Issue)

I have tried downgrading the Express version to 4 because some said the Express vr:5 is causing the error , but that didnt help ,

i checked all the routes & api endpoints but that didn't help either.

Gadget Routes :

// src/routes/gadget.routes.ts
import { Router } from 'express';
import { 
  getAllGadgets, 
  createGadget, 
  updateGadget, 
  decommissionGadget, 
  selfDestructGadget 
} from '../controllers/gadget.controller';
import { protect } from '../middleware/auth.middleware';

const router = Router();

// Apply authentication middleware to all routes
router.use(protect);

// Routes
router.get('/', getAllGadgets);
router.post('/', createGadget);
router.patch('/:id', updateGadget);
router.delete('/:id', decommissionGadget);
router.post('/:id/self-destruct', selfDestructGadget);

export default router;

app.ts :

import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import authRoutes from './routes/auth.routes';
import gadgetRoutes from './routes/gadget.routes';
import { AppError, handleError } from './utils/error.handler';

const app = express();

// Middleware
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Routes
app.use('/api/auth', authRoutes);
app.use('/api/gadgets', gadgetRoutes);

// Health check route
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'success', message: 'API is running' });
});

// Handle undefined routes
app.all('*', (req, res, next) => {
  next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});

// Global error handler
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  handleError(err, res);
});

export default app;

auth_routes.ts :

import { Router } from 'express';
import { body } from 'express-validator';
import { register, login } from '../controllers/auth.controller';
import { validate } from '../middleware/validate.middleware';

const router = Router();

// Validation rules
const registerValidation = [
  body('username')
    .notEmpty().withMessage('Username is required')
    .isLength({ min: 3 }).withMessage('Username must be at least 3 characters long'),
  body('password')
    .notEmpty().withMessage('Password is required')
    .isLength({ min: 6 }).withMessage('Password must be at least 6 characters long')
];

const loginValidation = [
  body('username').notEmpty().withMessage('Username is required'),
  body('password').notEmpty().withMessage('Password is required')
];

// Routes
router.post('/register', validate(registerValidation), register);
router.post('/login', validate(loginValidation), login);

export default router;

Auth_Middlewaree.ts :

import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { AppError } from '../utils/error.handler';
import prisma from '../utils/prisma.client';

interface JwtPayload {
  id: string;
}

declare global {
  namespace Express {
    interface Request {
      user?: {
        id: string;
      };
    }
  }
}

export const protect = async (req: Request, res: Response, next: NextFunction) => {
  try {
    // 1) Get token and check if it exists
    let token;
    if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
      token = req.headers.authorization.split(' ')[1];
    }

    if (!token) {
      return next(new AppError('You are not logged in. Please log in to get access', 401));
    }

    // 2) Verify token
    const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as JwtPayload;

    // 3) Check if user still exists
    const user = await prisma.user.findUnique({
      where: { id: decoded.id }
    });

    if (!user) {
      return next(new AppError('The user belonging to this token no longer exists', 401));
    }

    // 4) Grant access to protected route
    req.user = { id: user.id };
    next();
  } catch (error) {
    next(new AppError('Invalid token. Please log in again', 401));
  }
};

Gadget Controller Ts Code :

import { Request, Response, NextFunction } from 'express';
import { Status } from '@prisma/client'
import prisma from '../utils/prisma.client';
import { AppError } from '../utils/error.handler';

// Generate random codename for gadgets
const generateCodename = (): string => {
  const adjectives = ['Mighty', 'Silent', 'Phantom', 'Shadow', 'Stealth', 'Covert', 'Invisible', 'Deadly', 'Rapid', 'Quantum'];
  const nouns = ['Eagle', 'Panther', 'Cobra', 'Viper', 'Falcon', 'Wolf', 'Hawk', 'Tiger', 'Raven', 'Phoenix'];
  
  const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];
  const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];
  
  return `The ${randomAdjective} ${randomNoun}`;
};

// Generate random mission success probability
const generateMissionProbability = (): number => {
  return Math.floor(Math.random() * 100);
};

// Get all gadgets with optional status filter
export const getAllGadgets = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { status } = req.query;
    
    const whereClause = status ? { status: status as Status } : {};
    
    const gadgets = await prisma.gadget.findMany({
      where: whereClause
    });
    
    const gadgetsWithProbability = gadgets.map(gadget => ({
      ...gadget,
      missionSuccessProbability: generateMissionProbability()
    }));
    
    res.status(200).json({
      status: 'success',
      results: gadgetsWithProbability.length,
      data: {
        gadgets: gadgetsWithProbability
      }
    });
  } catch (error) {
    next(error);
  }
};

// Create a new gadget
export const createGadget = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { status } = req.body;
    
    const gadget = await prisma.gadget.create({
      data: {
        name: generateCodename(),
        status: status || 'Available'
      }
    });
    
    res.status(201).json({
      status: 'success',
      data: {
        gadget
      }
    });
  } catch (error) {
    next(error);
  }
};

// Update a gadget
export const updateGadget = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params;
    const { name, status } = req.body;
    
    const gadget = await prisma.gadget.findUnique({
      where: { id }
    });
    
    if (!gadget) {
      return next(new AppError('No gadget found with that ID', 404));
    }
    
    const updatedGadget = await prisma.gadget.update({
      where: { id },
      data: {
        name,
        status
      }
    });
    
    res.status(200).json({
      status: 'success',
      data: {
        gadget: updatedGadget
      }
    });
  } catch (error) {
    next(error);
  }
};

// Decommission a gadget (soft delete)
export const decommissionGadget = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params;
    
    const gadget = await prisma.gadget.findUnique({
      where: { id }
    });
    
    if (!gadget) {
      return next(new AppError('No gadget found with that ID', 404));
    }
    
    const decommissionedGadget = await prisma.gadget.update({
      where: { id },
      data: {
        status: 'Decommissioned',
        decomissionedAt: new Date()
      }
    });
    
    res.status(200).json({
      status: 'success',
      data: {
        gadget: decommissionedGadget
      }
    });
  } catch (error) {
    next(error);
  }
};

// Trigger self-destruct sequence for a gadget
export const selfDestructGadget = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params;
    
    const gadget = await prisma.gadget.findUnique({
      where: { id }
    });
    
    if (!gadget) {
      return next(new AppError('No gadget found with that ID', 404));
    }
    
    // Generate confirmation code
    const confirmationCode = Math.floor(100000 + Math.random() * 900000);
    
    const updatedGadget = await prisma.gadget.update({
      where: { id },
      data: {
        status: 'Destroyed',
        selfDestruct: new Date()
      }
    });
    
    res.status(200).json({
      status: 'success',
      confirmationCode,
      message: 'Self-destruct sequence initiated',
      data: {
        gadget: updatedGadget
      }
    });
  } catch (error) {
    next(error);
  }
};

The Gadgets Routes : 
router.get('/', getAllGadgets);
router.post('/', createGadget);
router.patch('/:id', updateGadget);
router.delete('/:id', decommissionGadget);
router.post('/:id/self-destruct', selfDestructGadget);

Even though i have no error in the routing , still i am getting the error :
throw new TypeError(Missing parameter name at ${i}: ${DEBUG_URL}); ^ TypeError: Missing parameter name at 1: https://git.new/pathToRegexpError

I possibly tried everything , GPT , V0 , StackOverFlow but the solutions didn't work.

Here is the package.json :

{
  "name": "pg_imp",
  "version": "1.0.0",
  "main": "dist/index.js",
  "scripts": {
    "start": "node dist/index.js",
    "dev": "ts-node-dev --respawn --transpile-only src/index.ts",
    "build": "tsc",
    "prisma:generate": "prisma generate",
    "prisma:migrate": "prisma migrate dev --name init"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "devDependencies": {
    "@types/bcrypt": "^5.0.2",
    "@types/cors": "^2.8.17",
    "@types/express": "^5.0.1",
    "@types/jsonwebtoken": "^9.0.9",
    "@types/uuid": "^10.0.0",
    "prisma": "^6.5.0",
    "ts-node-dev": "^2.0.0",
    "typescript": "^5.8.2"
  },
  "dependencies": {
    "@prisma/client": "^6.5.0",
    "bcrypt": "^5.1.1",
    "cors": "^2.8.5",
    "dotenv": "^16.4.7",
    "express": "^5.1.0",
    "express-validator": "^7.2.1",
    "helmet": "^8.1.0",
    "jsonwebtoken": "^9.0.2",
    "pg": "^8.14.1",
    "uuid": "^11.1.0"
  }
}


Can somebody please tell , how to fix the bug ! i am unable to fix this since 48Hrs (Skill Issue)

I have tried downgrading the Express version to 4 because some said the Express vr:5 is causing the error , but that didnt help ,

i checked all the routes & api endpoints but that didn't help either.

Gadget Routes :

// src/routes/gadget.routes.ts
import { Router } from 'express';
import { 
  getAllGadgets, 
  createGadget, 
  updateGadget, 
  decommissionGadget, 
  selfDestructGadget 
} from '../controllers/gadget.controller';
import { protect } from '../middleware/auth.middleware';

const router = Router();

// Apply authentication middleware to all routes
router.use(protect);

// Routes
router.get('/', getAllGadgets);
router.post('/', createGadget);
router.patch('/:id', updateGadget);
router.delete('/:id', decommissionGadget);
router.post('/:id/self-destruct', selfDestructGadget);

export default router;

app.ts :

import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import authRoutes from './routes/auth.routes';
import gadgetRoutes from './routes/gadget.routes';
import { AppError, handleError } from './utils/error.handler';

const app = express();

// Middleware
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Routes
app.use('/api/auth', authRoutes);
app.use('/api/gadgets', gadgetRoutes);

// Health check route
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'success', message: 'API is running' });
});

// Handle undefined routes
app.all('*', (req, res, next) => {
  next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});

// Global error handler
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  handleError(err, res);
});

export default app;

auth_routes.ts :

import { Router } from 'express';
import { body } from 'express-validator';
import { register, login } from '../controllers/auth.controller';
import { validate } from '../middleware/validate.middleware';

const router = Router();

// Validation rules
const registerValidation = [
  body('username')
    .notEmpty().withMessage('Username is required')
    .isLength({ min: 3 }).withMessage('Username must be at least 3 characters long'),
  body('password')
    .notEmpty().withMessage('Password is required')
    .isLength({ min: 6 }).withMessage('Password must be at least 6 characters long')
];

const loginValidation = [
  body('username').notEmpty().withMessage('Username is required'),
  body('password').notEmpty().withMessage('Password is required')
];

// Routes
router.post('/register', validate(registerValidation), register);
router.post('/login', validate(loginValidation), login);

export default router;

Auth_Middlewaree.ts :

import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { AppError } from '../utils/error.handler';
import prisma from '../utils/prisma.client';

interface JwtPayload {
  id: string;
}

declare global {
  namespace Express {
    interface Request {
      user?: {
        id: string;
      };
    }
  }
}

export const protect = async (req: Request, res: Response, next: NextFunction) => {
  try {
    // 1) Get token and check if it exists
    let token;
    if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
      token = req.headers.authorization.split(' ')[1];
    }

    if (!token) {
      return next(new AppError('You are not logged in. Please log in to get access', 401));
    }

    // 2) Verify token
    const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as JwtPayload;

    // 3) Check if user still exists
    const user = await prisma.user.findUnique({
      where: { id: decoded.id }
    });

    if (!user) {
      return next(new AppError('The user belonging to this token no longer exists', 401));
    }

    // 4) Grant access to protected route
    req.user = { id: user.id };
    next();
  } catch (error) {
    next(new AppError('Invalid token. Please log in again', 401));
  }
};
Share Improve this question edited 14 hours ago Surya asked 17 hours ago SuryaSurya 211 silver badge4 bronze badges 7
  • express js 5 (path-to-regexp) brings breaking changes, can u attach all the code snippets that calls express router ? eg (router.get/router.use/...) ? because one of em is using older format. You can learn more here – bogdanoff Commented 17 hours ago
  • Yeah Sure ! Let me Add all the Code that is calling express router – Surya Commented 14 hours ago
  • yeah i have added the files that are using express directly – Surya Commented 14 hours ago
  • @Surya Please, provide stackoverflow/help/mcve for your problem, it needs a way to reproduce. I believe this is currently impossible. Does the app have only 5 routes you listed? Did you try to comment out 4 of them and see what happens? It needs to be debugged on your side. You can start with checking what "str" is app.unpkg/[email protected]/files/dist/index.js#L73 in this place and comparing it against your routes, so you could narrow it down to a single route that causes the problem – Estus Flask Commented 14 hours ago
  • The best idea is to share you the drive link to all possible files and even the Prisma Schema to make the backend objective more clear. – Surya Commented 11 hours ago
 |  Show 2 more comments

1 Answer 1

Reset to default 1

Change the fallback router from

app.all('*', (req, res, next) => {})

to

app.all('/{*any}', (req, res, next) => {})

You can find related resources at Moving to Express 5

The wildcard * must have a name, matching the behavior of parameters :, use /*splat instead of /*

*splat matches any path without the root path. If you need to match the root path as well /, you can use /{*splat}, wrapping the wildcard in braces.

本文标签: nodejsthrow new TypeError(Missing parameter name at i DEBUGURL)Stack Overflow