2
votes

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)

4

4 Answers

4
votes

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

3
votes

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).

3
votes

I also recently faced this issue and it was because my project requires .env file which has all the base routes defined and somehow it was deleted from project. So my finding for this issue is check for all config/.env files which your node.js requires.

2
votes
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(); // <= Remove this line of code and it will work. you need the path parameter in order for a app.get() to work