0

I am learning to code in Node.js using express as framework. I got stucked all day long on a very simple thing: it looks like there is a problem with my class exportation, check this out:

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;

and also check the js file containing the class('../models/parola'):

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);
}

When the form get submitted and the user is therefor redirected on the '/process' page i always get the same error:

TypeError: Cannot read property 'par' of undefined at router.post (/home/marcwood/Scrivania/esame/routes/admin.js:13:31) at Layer.handle [as handle_request] (/home/marcwood/Scrivania/esame/node_modules/express/lib/router/layer.js:95:5) at next (/home/marcwood/Scrivania/esame/node_modules/express/lib/router/route.js:137:13)....

  • make `constructor(p){ par = p; };` not `this.par` in constructor – Sravan Dec 30 '19 at 15:19
  • I think you need to use `express.bodyParser()`. see: https://stackoverflow.com/questions/9177049/express-js-req-body-undefined – griFlo Dec 30 '19 at 15:21

0 Answers0