I’m learning Javascirrpt and I want to build a simple web app using forms.
At first the forms load nicely, but when I want to add something and click “add” an error pops up: Cannot read properties of undefined
Cannot read properties of undefined (reading ‘autor’) I do not really know why it can not “load the autor class”.
Basically, only the one line (marked in index.ejs class) is incorrect.
But, I’ve been wondering about this for a long time now and still have no idea how to fix it.
If someone could give me a hint, I would appreciate it.
app.js
const http = require('http');
const express = require('express');
const app = express();
var globalId = 0;
var person = [];
const bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index',{data:person});
});
app.post('/add',urlencodedParser, function(req, res) {
console.log("LN:" + req.body.LastName);
console.log("FN:" + req.body.FirstName);
console.log("T:" + req.body.Title);
var os = new os.autor(); ////////this line is wrong///////////
os.id = globalId++;
os.lastname = req.body.LastName;
os.name = req.body.FirstName;
os.title = req.body.Title;
person.push(os)
res.render('index', {data:person});
});
const server = http.createServer(app);
const port = 8000;
server.listen(port);
console.debug('Server listening on port ' + port);
index.ejs
<!DOCTYPE html>
<html lang="pl">
<head>
<title>Messages</title>
</head>
<body>
Autor:
<ul>
<% data.forEach(function(msg) { %>
<li>
</form action="/del/" method="post">
<%= msg.Sur %> <%= msg.Name %> Tit:<%= msg.Title %>
<input id="Id" type="hidden" name="Id" value="<%= msg.id %>">
<input type="submit" value="-">
</form>
</ll>>
<% }); %>
</ul>
<%if (data.length == 0) { %>
<p><no data!></p>
<% } %>
<br></br>
<form action="/add/" method="post">
<label for="frontmessage">Sur: </label>
<input id="LastName" type="text" name="LastName" value="Last Name...">
<label id="frontmessage">Name: </label>
<input id="FirstName" type="text" name="FirstName" value="First Name...">
<label id="frontmessage">Tit: </label>
<input id="Title" type="text" name="Title" value="Title...">
<input type="submit" value="Add">
</form>
</body>
</html>
autor.js
exports.autor = function(){
id:Number;
lastname:String;
firstname:String;
title:String;
};
exports.sum = function(a, b) {
return a + b;
};