Exerciții
Instalăm NodeJS
Verificăm în linia de comandă (Command Prompt în windows) dacă avem acces la node: node -v
(trebuie să primim versiunea de nodejs)
Într-un director nou vom crea un proiect nou cu:
npm init
acceptăm opțiunile default (enter)
Instalăm pachetele express și express-handlebars
npm install express express-handlebars
Verificăm fișierul package.json
, ar trebui să vedem la dependencies express și express-handlebars:
{
"name": "mpa",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.3",
"express-handlebars": "^3.0.0"
}
}
Adăugăm un fișier nou: index.js
const express = require('express');
const exphbs = require('express-handlebars');
const app = express();
// set static dir
app.use(express.static('public'));
// config handlebars
app.engine('handlebars', exphbs({
defaultLayout: 'main'
}));
app.set('view engine', 'handlebars');
// set routes
app.get('/', function(req, res) {
res.render('home', {
pageTitle: 'Home page'
});
});
app.get('/about', function(req, res) {
res.render('about', {
pageTitle: 'About page'
});
});
app.get('/contact', function(req, res) {
res.render('contact', {
pageTitle: 'Contact page'
});
});
app.get('/handle-form', function(req, res) {
res.render('handleForm', {
pageTitle: 'Contact page',
query: req.query
});
});
// run server
app.listen(3000, function(){
console.log('Server is running...');
});
Adăugăm fișierul views/layouts/main.handlebars
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ pageTitle }}</title>
</head>
<body>
<h1>{{ pageTitle }}</h1>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
{{{ body }}}
<script src="static.js"></script>
</body>
</html>
Adăugăm fișierul views/home.handlebars
:
<h2>you are at home.</h2>
Adăugăm fișierul views/about.handlebars
:
<h2>you are on about me page.</h2>
Adăugăm fișierul views/contact.handlebars
:
<form action="handle-form" method="get">
<p>Name <input type="text" name="name"></p>
<input type="email" name="email">
textarea message
<button type="submit">Send</button>
</form>
Adăugăm fișierul views/handleForm.handlebars
:
<p>Name: {{ query.name }}</p>
<p>Email: {{ query.email }}</p>
<script>
const user = {
name: '{{ query.name }}',
email: '{{ query.email }}'
}
</script>
Adăugăm fișierul public/static.js
:
console.log('You are client.');
Pornim serverul:
node index.js
Accesăm din browser:
localhost:3000