Olá galera! Neste artigo, criaremos um Website Single Page utilizando NodeJS.
Para criar este projeto, precisaremos de:
- NodeJS + NPM;
- Um editor de código de sua preferência. Recomendo utilizar o Visual Studio Code.
Vamos começar!
De início, precisamos criar nossa pasta que conterá todos os arquivos do projeto. Utilizando um terminal, crie a pasta chamada node_website com o comando:
mkdir node_website
cd node_website
Dentro da nossa pasta, criaremos dois arquivos:
- package.json (conterá nossas dependências);
- server.js (conterá nossos scripts para criação do servidor).
Crie também uma pasta chamada node-example-website e, dentro desta pasta, crie outra pasta chamada express. Essa pasta express conterá nosso arquivo index.html.
Ao código!
No nosso arquivo package.json, precisamos adicionar o nome do nosso projeto, versão, os scripts e as dependências. O seu arquivo deverá ficar assim:
{
"name": "node-website",
"version": "1.0.0",
"description": "",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.17.1"
}
}
Assim, já criamos nosso arquivo de dependências.
Agora, precisamos criar nosso servidor. No nosso arquivo server.js, iremos:
- Fazer a requisição dos pacotes que utilizaremos;
- Criaremos o servidor na porta que escolhermos utilizar.
const http = require('http');
const express = require('express');
const path = require('path');
const app = express();
app.use(express.json());
app.use(express.static('express'));
// URL padrão do site
app.use('/', (req, res) => {
res.sendFile(path.join(__dirname+'/node-example-website/express/index.html'));
});
const server = http.createServer(app);
const port = 3000;
server.listen(port);
console.debug('Server inicializado na porta ' + port);
Neste projeto, estamos utilizando a porta 3000.
Agora, precisamos instalar as outras dependências e módulos do node no nosso projeto. Dentro da pasta node-example-website, rode o seguinte comando:
npm install
Esse comando vai instalar as dependências definidas no nosso package.json.
No nosso arquivo index.html, utilizaremos um exemplo do W3CSS, chamado Cafe Template. Você pode utilizar o template de sua preferência ou criar o seu próprio!
<!DOCTYPE html>
<html>
<title>W3.CSS Template</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Inconsolata">
<style>
body, html {
height: 100%;
font-family: "Inconsolata", sans-serif;
}
.bgimg {
background-position: center;
background-size: cover;
background-image: url("https://www.w3schools.com/w3images/coffeehouse.jpg");
min-height: 75%;
}
.menu {
display: none;
}
</style>
<body>
<!-- Links (sit on top) -->
<div class="w3-top">
<div class="w3-row w3-padding w3-black">
<div class="w3-col s3">
<a href="#" class="w3-button w3-block w3-black">HOME</a>
</div>
<div class="w3-col s3">
<a href="#about" class="w3-button w3-block w3-black">ABOUT</a>
</div>
<div class="w3-col s3">
<a href="#menu" class="w3-button w3-block w3-black">MENU</a>
</div>
<div class="w3-col s3">
<a href="#where" class="w3-button w3-block w3-black">WHERE</a>
</div>
</div>
</div>
<!-- Header with image -->
<header class="bgimg w3-display-container w3-grayscale-min" id="home">
<div class="w3-display-bottomleft w3-center w3-padding-large w3-hide-small">
<span class="w3-tag">Open from 6am to 5pm</span>
</div>
<div class="w3-display-middle w3-center">
<span class="w3-text-white" style="font-size:90px">the<br>Cafe</span>
</div>
<div class="w3-display-bottomright w3-center w3-padding-large">
<span class="w3-text-white">15 Adr street, 5015</span>
</div>
</header>
<!-- Add a background color and large text to the whole page -->
<div class="w3-sand w3-grayscale w3-large">
<!-- About Container -->
<div class="w3-container" id="about">
<div class="w3-content" style="max-width:700px">
<h5 class="w3-center w3-padding-64"><span class="w3-tag w3-wide">ABOUT THE CAFE</span></h5>
<p>The Cafe was founded in blabla by Mr. Smith in lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<p>In addition to our full espresso and brew bar menu, we serve fresh made-to-order breakfast and lunch sandwiches, as well as a selection of sides and salads and other good stuff.</p>
<div class="w3-panel w3-leftbar w3-light-grey">
<p><i>"Use products from nature for what it's worth - but never too early, nor too late." Fresh is the new sweet.</i></p>
<p>Chef, Coffeeist and Owner: Liam Brown</p>
</div>
<img src="https://www.w3schools.com/w3images/coffeeshop.jpg" style="width:100%;max-width:1000px" class="w3-margin-top">
<p><strong>Opening hours:</strong> everyday from 6am to 5pm.</p>
<p><strong>Address:</strong> 15 Adr street, 5015, NY</p>
</div>
</div>
<!-- Menu Container -->
<div class="w3-container" id="menu">
<div class="w3-content" style="max-width:700px">
<h5 class="w3-center w3-padding-48"><span class="w3-tag w3-wide">THE MENU</span></h5>
<div class="w3-row w3-center w3-card w3-padding">
<a href="javascript:void(0)" onclick="openMenu(event, 'Eat');" id="myLink">
<div class="w3-col s6 tablink">Eat</div>
</a>
<a href="javascript:void(0)" onclick="openMenu(event, 'Drinks');">
<div class="w3-col s6 tablink">Drink</div>
</a>
</div>
<div id="Eat" class="w3-container menu w3-padding-48 w3-card">
<h5>Bread Basket</h5>
<p class="w3-text-grey">Assortment of fresh baked fruit breads and muffins 5.50</p><br>
<h5>Honey Almond Granola with Fruits</h5>
<p class="w3-text-grey">Natural cereal of honey toasted oats, raisins, almonds and dates 7.00</p><br>
<h5>Belgian Waffle</h5>
<p class="w3-text-grey">Vanilla flavored batter with malted flour 7.50</p><br>
<h5>Scrambled eggs</h5>
<p class="w3-text-grey">Scrambled eggs, roasted red pepper and garlic, with green onions 7.50</p><br>
<h5>Blueberry Pancakes</h5>
<p class="w3-text-grey">With syrup, butter and lots of berries 8.50</p>
</div>
<div id="Drinks" class="w3-container menu w3-padding-48 w3-card">
<h5>Coffee</h5>
<p class="w3-text-grey">Regular coffee 2.50</p><br>
<h5>Chocolato</h5>
<p class="w3-text-grey">Chocolate espresso with milk 4.50</p><br>
<h5>Corretto</h5>
<p class="w3-text-grey">Whiskey and coffee 5.00</p><br>
<h5>Iced tea</h5>
<p class="w3-text-grey">Hot tea, except not hot 3.00</p><br>
<h5>Soda</h5>
<p class="w3-text-grey">Coke, Sprite, Fanta, etc. 2.50</p>
</div>
<img src="https://www.w3schools.com/w3images/coffeehouse2.jpg" style="width:100%;max-width:1000px;margin-top:32px;">
</div>
</div>
<!-- Contact/Area Container -->
<div class="w3-container" id="where" style="padding-bottom:32px;">
<div class="w3-content" style="max-width:700px">
<h5 class="w3-center w3-padding-48"><span class="w3-tag w3-wide">WHERE TO FIND US</span></h5>
<p>Find us at some address at some place.</p>
<img src="https://www.w3schools.com/w3images/map.jpg" class="w3-image" style="width:100%">
<p><span class="w3-tag">FYI!</span> We offer full-service catering for any event, large or small. We understand your needs and we will cater the food to satisfy the biggerst criteria of them all, both look and taste.</p>
<p><strong>Reserve</strong> a table, ask for today's special or just send us a message:</p>
<form action="/action_page.php" target="_blank">
<p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Name" required name="Name"></p>
<p><input class="w3-input w3-padding-16 w3-border" type="number" placeholder="How many people" required name="People"></p>
<p><input class="w3-input w3-padding-16 w3-border" type="datetime-local" placeholder="Date and time" required name="date" value="2017-11-16T20:00"></p>
<p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Message \ Special requirements" required name="Message"></p>
<p><button class="w3-button w3-black" type="submit">SEND MESSAGE</button></p>
</form>
</div>
</div>
<!-- End page content -->
</div>
<!-- Footer -->
<footer class="w3-center w3-light-grey w3-padding-48 w3-large">
<p>Powered by <a href="https://www.w3schools.com/w3css/default.asp" title="W3.CSS" target="_blank" class="w3-hover-text-green">w3.css</a></p>
</footer>
<script>
// Tabbed Menu
function openMenu(evt, menuName) {
var i, x, tablinks;
x = document.getElementsByClassName("menu");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < x.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" w3-dark-grey", "");
}
document.getElementById(menuName).style.display = "block";
evt.currentTarget.firstElementChild.className += " w3-dark-grey";
}
document.getElementById("myLink").click();
</script>
</body>
</html>
Você também pode adicionar o css e js em arquivos separados!
Para inicializar o servidor, utilizamos o comando:
npm start
Para testar, abra o seu browser e digite:
localhost:3000
E veja o seu site rodando!
Gostou deste artigo? Comente abaixo com seus amigos!
Referências: