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)
5条答案
按热度按时间mwkjh3gx1#
该错误背后的原因是使用了不带param的
app.get()
方法,该方法需要端点url和回调作为参数。iqih9akk2#
app.get();
导致错误。正如文档所述,
app.get(path, callback [, callback ...])
必须有一个路径参数(app.get(name)
也必须有名称参数)。vpfxa7rd3#
我最近也遇到了这个问题,这是因为我的项目需要.env文件,其中定义了所有的基本路线,但不知何故,它被从项目中删除。因此,我发现这个问题是检查所有的配置/.env文件,您的node.js需要。
9cbw7uwe4#
r7knjye25#
可能检查app.get()和app.post()是否被留下任何边界尝试注解它并检查正如文档所述,app.get(path,callback [,callback ...])必须有路径参数(app.get(name)也必须有名称参数)。