如何修复“无法读取未定义的属性推送"; Nodejs中的错误? [英] how to fix "can't read property push of undefined" error in Nodejs?
问题描述
我已经编写了一个简单的应用程序来学习Nodejs,但是当我在cmd中运行"nodemon index.js"时,出现此错误 TypeError:无法读取未定义的属性"push" 应用程序崩溃-等待文件更改,然后再开始...
I have coded a simple app to learn Nodejs but when i run "nodemon index.js" in cmd i have this error TypeError: Cannot read property 'push' of undefined app crashed - waiting for file changes before starting...
我已按照udemy课程中的所有说明来学习Node.js 当我将文件分为两个文件index.js和genres.js
i have follow all instruction in the udemy course for learn nodejs and i faced this problem when i separated the file into two files index.js and genres.js
genres.js
genres.js
const express = require('express');
const router = express.Router;
//simple data
const genres = [{
id: 1,
name: 'course1'
},
{
id: 2,
name: 'course2'
},
{
id: 3,
name: 'course3'
}
];
//////////////////////////////////////////////////////////////////////
/////////////////////////////////// Get //////////////////////////////
//////////////////////////////////////////////////////////////////////
router.get('/', (req, res) => {
res.send(genres);
});
router.get('/:id', (req, res) => {
const genre = genres.find(c => c.id ===
parseInt(req.params.id)); //req.params.id return string
if (!genre)
return res.status(404).send('The course is not found...');
res.send(genre);
res.send(req.params.id);
});
router.get('/:year/:month', (req, res) => {
res.send(req.params);
});
router.post('/', (req, res) => {
const {
error
} = validategenre(req.body);
if (error)
return res.status(400).send(error.details[0].message);
const genre = {
id: genres.length + 1,
name: req.body.name
}
genres.push(genre);
res.send(genre);
});
router.put('/:id', (req, res) => {
const genre = genres.find(c => c.id === parseInt(req.params.id));
if (!genre)
return res.status(404).send('The course does not exist !!! ');
const result = validategenre(req.body);
if (result.error)
return res.status(400).send(result.error.details[0].message);
genre.name = req.body.name;
res.send(genre);
});
function validategenre(genre) {
const schema = {
name: Joi.string().min(3).required()
};
return Joi.validate(genre, schema);
}
module.exports = router;
index.js
const Joi = require('joi');
const genres = require('./routes/genres');
const express = require('express');
const app = express();
app.use(express.json());
app.use('/api/genres', genres);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listining on port ${port}...`));
推荐答案
在genres.js中,您应该导入
In genres.js, you should import
const router = express.Router();
代替
const router = express.Router;
另外,您提到的错误可能是代码中的任何push
(没有更多信息),请下次指定stacktrace:)
Also, the error you mention could be from any push
in your code (without any more info), please specify the stacktrace next time :)
这篇关于如何修复“无法读取未定义的属性推送"; Nodejs中的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!