Tarefas a realizar na aula:
Apresentação dos slides do JSON-Server: requests put e delete;
Introdução ao Express:
$ mkdir myapp
$ cd myapp
$ npm init
entry point: (index.js) app.js
...
$ npm i express --save
$ vim app.js
...
$ node app.js
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
$ npx express-generator --view=pug
A estrutura da aplicação;
O pipeline de execução;
O conceito de roteador;
"Emagrecer" a aplicação;
Recriar a aplicação dos alunos nesta estrutura:
View: layout.pug
doctype html
html
head
title Student Management
meta(charset="UTF-8")
link(rel="icon" href="/images/favicon.png")
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
View: index.pug
extends layout
block content
.w3-card-4
header.w3-container.w3-teal
h1 Students List #[a.w3-button.w3-round(href="/alunos/registo") +]
.w3-container
table.w3-table-all
tr
th Id
th Name
th GitLink
th Actions
each s in slist
tr
td= s.id
td
a(href="/alunos/" + s.id)= s.nome
td
a(href=s.gitlink) GitHub Link
td
button.w3-btn.w3-round.w3-indigo.w3-margin-right
a(href="/alunos/edit/" + s.id) Edit
button.w3-btn.w3-round.w3-indigo
a(href="/alunos/delete/" + s.id) Delete
footer.w3-container.w3-teal
h5 Generated by RPCW2023 in #{d}q
Router: index.js
var express = require('express');
var router = express.Router();
var Aluno = require('../controllers/aluno')
/* GET home page. */
router.get('/', function(req, res) {
var mydate = new Date().toISOString().substring(0, 16)
Aluno.list()
.then(alunos => {
res.render('index', { slist: alunos, d: mydate });
})
.catch(erro => {
res.render('error', {message: "Erro na recuperação da lista de alunos!"})
})
});
Controller: aluno.js
var axios = require('axios')
// Student List
module.exports.list = () => {
return axios.get("http://localhost:3000/alunos?_sort=nome")
.then(response => {
return response.data
})
.catch(function(erro){
return erro
})
}
// Student Record
module.exports.getAluno = (id) => {
return axios.get("http://localhost:3000/alunos/" + id)
.then(response => {
return response.data
})
.catch(function(erro){
return erro
})
}
// Student Record Add
module.exports.addAluno = (a) => {
return axios.post("http://localhost:3000/alunos", a)
.then(response => {
return response.data
})
.catch(function(erro){
return erro
})
}
Fazer o resto da aplicação...