Let's learn how to use javascript to program a server based on Node.js and upload the website to Heroku. First, a simple server; write this in a file called app.js:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Then in a file called .gitignore we will write this:
node_modules
Lastly, let's install express, our server framework.
npm install express --save
We will also install nodemon since it makes things much easier:
npm install nodemon -g
Now we can see that message on the server. Run nodemon and open localhost:3000:
nodemon
Routing
Now let's tell our server what files and how it should display. First let's just display index.html. In app.js, write this instead of our previous 'Hello world':
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
If we reopen localhost:3000 and refresh it we can see our index.html without any style or javascript.
Then we also want our server to know where our css and (front-end) javascript is, so we will add this and put those files in there:
app.use(express.static('public'));
Now let's catch the files dynamically (routing). We will get the url fragment as the variable path and then use it:
app.get('/:name', function (req, res) {
console.log(req.params);
res.send(req.params);
});
The previous one only shows us in the terminal what file we are reading, now let's actually show it:
app.get('/:name', function (req, res) {
var file = __dirname + '/' + req.params.nombre + '.html';
res.sendFile(file);
});
Post
Vamos a probar a enviar un formulario y recuperarlo. Primero nos creamos el formulario en "contact.html":
<!DOCTYPE html> <html> <head> <title>Página Web</title> <meta charset="utf-8"> <meta name='viewport' content='width=device-width, initial-scale=1'> <link rel="stylesheet" href="https://cdn.jsdelivr.net/picnicss/6.1.1/picnic.min.css"> <link rel="stylesheet" href="style.css"> </head> <body> <form action="/contacto" method="POST" class="contact"> <h1>Contacto</h1> <input placeholder="Nombre"> <input placeholder="Apellidos"> <input placeholder="Edad"> <input type="submit" value="Enviar"> </form> </body> </html
Y en "style.css":
.contact { width: 500px; margin: 100px auto; } .contact input { margin-top: 0; margin-bottom: 10px; }
Instalar el modulo de lectura de datos de formulario:
npm install body-parser --save
Después en app.js:
var bodyparser = require('body-parser'); app.use(bodyparser.urlencoded({ extended: false }));
Estructura:
<main> <div class="gallery"> <div class="flex three"> <div class="element" data-id="1"> <img src="/images/mandarinas.jpg"> <button class="like">Like</button> <button class="dislike error">Dislike</button> </div> <div class="element" data-id="2"> <img src="/images/naranjas.jpg"> <button class="like">Like</button> <button class="dislike error">Dislike</button> </div> <div class="element" data-id="3"> <img src="/images/mandarinas.jpg"> <button class="like">Like</button> <button class="dislike error">Dislike</button> </div> </div> </div> </main>
Ejercicio: hacer un botón de dislike que llame a la ruta "/dislike" por POST y muestre en la consola del navegador lo que devuelve el servidor.