gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'push' of undefined -Express

转载 作者:数据小太阳 更新时间:2023-10-29 05:24:47 29 4
gpt4 key购买 nike

我已经为使用 express 路由和创建服务器的 nodejs 应用程序编写了两个 Javascript 文件。由于我是初学者,我对此了解不多。当我运行该应用程序时,它向我显示以下错误:-

/usr/lib/node_modules/express/lib/router/index.js:472
this.stack.push(layer);
^

TypeError: Cannot read property 'push' of undefined
at Function.use (/usr/lib/node_modules/express/lib/router/index.js:472:15)
at Object.<anonymous> (/home/dhiresh/Coding/angularjsapp/api.js:9:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/home/dhiresh/Coding/angularjsapp/index.js:2:7)

index.js 文件如下:-

var express = require('express'),
api = require('./api'),
app=express();

app
.use(express.static('./public'))
.use('/api',api)
.get('*',function (req,res) {
res.sendfile('public/index.html');
}).listen(3000);

api.js 文件如下:-

var express = require('express'),
bourne = require('bourne'),
bodyParser= require('body-parser'),

db = new bourne('data.json'),

router =express.Router();

router
.use(function(req,res,next){
if(!req.user) req.user={ id:1 };
next();
})
.use(bodyParser.json())
.route('/contact')
.get(function(req,res){
db.find({userId : parseInt(req.user.id,10)},function(err,data){
res.json(data);
});
})
.post(function(req,res){
var contact = req.body;
contact.userId = req.user.id;

db.insert(contact,function(err,data){
res.json(data);
});
});

router
.param('id',function(req,res,next){
req.dbQuery = { id:parseInt(req.params.id,10) }
})
.route('/contact/:id')
.get(function(req,res){
db.findOne(req.dbQuery,function(err,data){
res.json(data);
});
})
.put(function(req,res){
var contact = req.body;
delete contact.$promise;
delete contact.$resolve;
db.update(req.dbQuery,function(err,data){
res.json(data[0]);
})
})
.delete(function(req,res){
db.delete(req.dbQuery,function(err,data){
res.json(null);
})
});

module.exports = router;

谁能告诉我这个问题的答案。

最佳答案

我的问题是缺少括号:

const router = require('express').Router;

将此更改为

const router = require('express').Router(); 

解决了我的问题。

关于javascript - 类型错误 : Cannot read property 'push' of undefined -Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45660859/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com