我试图通过使用Handlebars作为视图引擎的处方集将数据放入数据库,当我单击按钮发送数据时,出现此错误消息:TypeError:无法读取未定义的属性(阅读“matricula”)。
这是我创建“Alunos”表的迁移文件:
module.exports = {
up: async (queryInterface, Sequelize) => {
return queryInterface.createTable('alunos', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
matricula: {
type: Sequelize.INTEGER,
allowNull: false,
},
nome: {
type: Sequelize.STRING,
allowNull: false,
},
curso: {
type: Sequelize.STRING,
allowNull: false,
},
ano: {
type: Sequelize.INTEGER,
allowNull: false,
},
createdAt: {
type: Sequelize.DATE,
},
updatedAt: {
type: Sequelize.DATE,
},
});
},
down: async (queryInterface, Sequelize) => {
return queryInterface.dropTable('alunos');
}
};
这是Aluno的模型:
const { DataTypes } = require('sequelize');
const sequelize = require('../config/sequelize');
const Aluno = sequelize.define('alunos', {
matricula: DataTypes.INTEGER,
nome: DataTypes.STRING,
curso: DataTypes.STRING,
ano: DataTypes.INTEGER,
});
module.exports = Aluno;
下面是config.js文件:
module.exports = {
dialect: 'postgres',
host: 'localhost',
username: 'postgres',
password: '123456',
database: 'novoProjeto',
define: {
timestamps: true,
},
};
这是sequelize.js文件:
const database = require('./config');
const Sequelize = require('sequelize');
const sequelize = new Sequelize(database);
sequelize.authenticate().then(function(){
//message if connects
console.log('Conexão executada com o banco de dados.')
}).catch(function(err){
//message if it doesn't
console.log('Conexão não executada com o banco de dados devido a: ' + err)
});
module.exports = sequelize;
下面是index.js文件:
const express = require('express');
const app = express();
const { engine } = require('express-handlebars');
const bodyParser = require('body-parser');
const routes = require('./routes/routes');
app.use(routes);
//Config
//Template Config
app.engine('handlebars', engine({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
//Body Parser
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen(3000);
下面是routes.js文件:
const express = require('express');
const routes = express.Router();
const AlunoController = require('../Controller/AlunoController');
//Home page
routes.get('/', function(req, res){
res.send('Home page')
});
// Routes for Aluno's data
//Final register page
routes.post('/add-aluno', function(req, res){
//This is where the error goes
res.send(`Data sent. Matricula: ${req.body.matricula} ;Nome: ${req.body.nome}; Curso: ${req.body.curso}; Ano: ${req.body.ano}`)
});
//Mostrar alunos cadastrados
routes.get('/show-alunos', function(req, res){
AlunoController.index
});
//Atualizar dados de aluno específico
routes.put('/upd-aluno/:id', function(req, res){
AlunoController.put
});
//Deletar dados de aluno específico
routes.delete('/del-aluno/:id', function(req, res){
AlunoController.delete
});
//Rota para formulário de cadastro de alunos
routes.get('/cad-aluno', function(req, res){
res.render('formulario')
});
module.exports = routes;
下面是表单.handlebars文件:
<form action="/add-aluno" method="post">
<label>Matrícula: </label>
<br>
<input type="text" name="matricula" placeholder="Ex.: 0001122">
<br>
<label>Nome: </label>
<br>
<input type="text" name="nome" placeholder="Ex.: João Guilherme...">
<br>
<label>Curso: </label>
<br>
<input type="text" name="curso" placeholder="Ex.: Enfermagem">
<br>
<label>Ano: </label>
<br>
<input type="text" name="ano" placeholder="Ex.: 2">
<button type="submit">Enviar</button>
</form>
我不知道我能在这里做什么。主要的错误是在routes.js文件中。在将数据发送到数据库之前,我尝试发送一条消息,显示字段中的4个信息,是这些:入学考试,名,课程,名。但是它什么也没有显示,因为它说它是未定义的。有人能帮忙吗?
一些//评论是葡萄牙语的,我翻译了那些你应该阅读的只是为了方便。
1条答案
按热度按时间jhdbpxl91#
在index.js文件中,
app.use(routes)
行在app.use(bodyParser.json())
行之前。为了让express从请求正文中提取数据,它需要事先通过bodyParser中间件。如果将app.use(routes)
行移到app.listen(3000)
行之前,它应该可以工作。另外,顺便说一下,你不需要再安装bodyParser库了,因为它现在已经内置到Express中了。你可以替换以下行:
用这个代替: