node.js - 无法在 Node.js 中使用类和保存数据
问题描述
我正在学习使用 express 作为框架在 Node.js 中编码。我整天都被一件非常简单的事情困住了:看起来我的班级导出有问题,请检查一下:
const express= require('express');
const router = express.Router();
const Nome = require('../models/parola')
router.get('/',(req,res,next)=>{
res.render('home');
});
router.post('/process',(req,res,next)=>{
const nomi= new Nome(req.body.par);
nomi.save();
res.redirect('/lista');
router.get('/',(req,res,next)=>{
res.render('lista');
});
});
module.exports=router;
并检查包含类('../models/parola')的js文件:
const path=require('path');
const fs= require('fs');
const p = path.join(path.dirname(process.mainModule.filename), 'data','saving.json');
const getFile = cb =>{
fs.readFile(p,(err,fileContent)=>{
if (err) {
cb([]);
}else{
cb(JSON.parse(fileContent));
}
});
module.exports = class Nome{
constructor(p){
this.par = p;
};
save ()
{
getFile(nomi=>{
nomi.push(this);
fs.writeFile(p,JSON.stringify(nomi),err=>{
console.log(err);
});
});
}
static fetchAll(){
getFile(cb);
}
当表单被提交并且用户因此被重定向到“/进程”页面时,我总是得到同样的错误:
TypeError:无法在 Layer.handle [as handle_request] (/home/marcwood/Scrivania/ esame/node_modules/express/lib/router/layer.js:95:5) 在下一个 (/home/marcwood/Scrivania/esame/node_modules/express/lib/router/route.js:137:13) ....
解决方案
推荐阅读
- ruby-on-rails - Rails应用程序中的多表查询搜索功能
- css - CSS:格式化内部元素的问题
- javascript - 视频无法在 ios (safari) 上播放
- jackson-databind - @JsonAppend 虚拟属性——ObjectReader 尊重它吗?
- python - Python 标头请求错误的内容类型/错误 404
- apache-kafka - Kafka Azure Blob Storage Sink Connector over VPN
- python - 为什么 vimspector 不会在 Python Flask 中的断点处停止
- amazon-web-services - GitLab 作业在 GitLab CI/CD 管道期间引发“错误:已保存的计划已过时”错误
- django - Django切换数据库用户
- powershell - 如何在不更改格式的情况下从 powershell 更新 yaml 文件?