Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

General `NodeJs/express` Error when declaring routes (TypeError: Cannot read property 'length' of undefined at pathtoRegexp)

I'm new at node.js, and this error cost me many efforts of investigations so I'm sharing this.

I've only tried to declare the express and some basic routers in my index.js:

const express = require('express');
const app = express();

app.get('/api/courses', (req, res)=>{
    res.send(courses);
});

app.get('/api/courses:id', (req, res)=>{
    const course = courses.find(c => c.id === parseInt(req.params.id));
    if (!course) res.send('The given id was not found...');
    res.send(course);   
});

app.get();

The error details:

\node_modules\path-to-regexp\index.js:63 path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?')) ^

TypeError: Cannot read property 'length' of undefined at pathtoRegexp (C:\Users...\node_modules\path-to-regexp\index.js:63:49) at new Layer (C:\Users...\node_modules\express\lib\router\layer.js:45:17) at Function.route (C:\Users...\node_modules\express\lib\router\index.js:494:15) at Function.app.(anonymous function) [as get] (C:\Users...\node_modules\express\lib\application.js:481:30) at Object. (C:...\index.js:24:5) at Module._compile (module.js:652:30) at Object.Module._extensions..js (module.js:663:10) at Module.load (module.js:565:32) at tryModuleLoad (module.js:505:12) at Function.Module._load (module.js:497:3)

like image 265
Shahar Shokrani Avatar asked Oct 28 '25 09:10

Shahar Shokrani


2 Answers

The reason behind that error is using the app.get() method without param, which expect the endpoint url and call back as parameters.

like image 168
Ahsan Avatar answered Oct 29 '25 23:10

Ahsan


The app.get(); causes the error.

As the documentation says, the app.get(path, callback [, callback ...]) must have a path argument (also app.get(name) must have name argument).

like image 39
Shahar Shokrani Avatar answered Oct 29 '25 23:10

Shahar Shokrani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!