Advertisement
Foxx3r

Express.js

May 25th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/node
  2.  
  3.         /*      CARREGAR        MÓDULOS         */
  4. const express = require('express');
  5. const app = express();
  6. const handlebars = require('express-handlebars');
  7. const bodyParser = require('body-parser');;
  8. const Post = require('./models/Post');
  9. const Mongoc = ('./mongo');
  10.  
  11.         /* variavel de armazenamento de datas   */
  12. var d = new Date();
  13. var B = d.toUTCString();
  14.  
  15.         /*      Body Parser Config      */
  16. app.use(bodyParser.urlencoded({extended: false}));
  17. app.use(bodyParser.json());
  18.  
  19.         /*      CONFIG   TEMPLATE       */
  20. app.engine('handlebars', handlebars({defaultLayout: 'main'}));
  21. app.set('view engine', 'handlebars');
  22.  
  23.         /*      ROTAS   */
  24. app.get("/", (req, res) => {
  25.         Post.findAll({order: [['id', 'DESC']]}).then( (posts) => {
  26.                 res.render('home', {posts: posts});
  27.         })
  28. });
  29.  
  30. app.get("/login", (req, res) => {
  31.         res.render('formulario');
  32. });
  33.  
  34. app.post("/post", (req, res) => {
  35.         Post.create({
  36.                 titulo: req.body.titulo,
  37.                 conteudo: req.body.conteudo
  38.         }).then( () => {
  39.                 res.redirect("/");
  40.     }).catch( (erro) => {
  41.                 res.send("Houve um erro: " + erro);
  42.     })
  43. });
  44.  
  45. app.get("/wiki", (req, res) => {
  46.         res.sendFile(__dirname + "/html/index.html");
  47. });
  48.  
  49. app.get("/documentacao/:nome/:cargo", (req, res) => {
  50.         res.send(req.params);
  51. });
  52.  
  53. app.get("/facebook/:nome", (req, res) => {
  54.         res.send("<img src=\"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcScxsT5PAXXm9mSG5PCxHh9nR4hGpiwldBqyf54h8Hiwkxpf9bZ\" width=\"100%\">");
  55. });
  56.  
  57.  
  58. app.get("/deletar/:id", (req, res) => {
  59.         Post.destroy({where: {'id': req.params.id}}).then( () => {
  60.                 res.send("Post deletado com sucesso!");
  61.         }).catch( (erro) => {
  62.                 res.send("Esta postagem não existe mais");
  63.         })
  64. });
  65.  
  66.         /*       EXECUTAR SERVIDOR EM DETERMINADA PORTA         */
  67. app.listen(8080, () => {
  68.         console.log("[" + B + "]: " +"Servidor rodando no endereço localhost:8080");
  69. });
  70.  
  71.  
  72.  
  73.  
  74. /* VIEWS */
  75. //VIEW formulario.handlebars
  76. <form action="/post" method="POST">
  77.         <p>Titulo: </p>
  78.         <input type="text" name="titulo">
  79.         <p>Conteüdo: </p>
  80.         <textarea name="conteudo"></textarea>
  81.         <button type="submit">Postar</button>
  82. </form>
  83.  
  84. // VIEW main.handlebars
  85. !DOCTYPE html>
  86. <html   lang="pt-br">
  87. <head>
  88.         <meta charset="utf-8" />
  89.         <title>Postagens Nodejs</title>
  90.         <style type="text/css">
  91.  
  92.  
  93.         </style>
  94.  
  95. </head>
  96. <body>
  97. {{{body}}}
  98.  
  99. <script type="text/javascript">
  100.  
  101.  
  102. </script>
  103.  
  104. </body>
  105. </html>
  106.  
  107. // VIEW home.handlebars
  108. <h1>Lista de postagens: </h1>
  109. <hr/>
  110.  
  111. {{#each posts}}
  112.  
  113.         <small>{{createdAt}}</small>
  114.         <h2>{{titulo}}</h2>
  115.         <p>{{conteudo}}</p>
  116.         <a href="/deletar/{{id}}"><button>Deletar</button></a>
  117.         <hr/>
  118.  
  119. {{/each}}
  120.  
  121. /* FIM VIEWS */
  122.  
  123. /* MODELS */
  124. // MODEL Post.js
  125. const db = require('./db');
  126.  
  127. const Post = db.sequelize.define('postagens', {
  128.         titulo: {
  129.                 type: db.Sequelize.STRING
  130.         },
  131.         conteudo: {
  132.                 type: db.Sequelize.TEXT
  133.         }
  134. });
  135.  
  136. //Post.sync({force: true});
  137.  
  138. module.exports = Post;
  139.  
  140. // MODEL db.js
  141. /*       CONEXÃO COM O BANCO DE DADOS           */
  142. const Sequelize = require('sequelize');
  143. const sequelize = new Sequelize
  144. ("postagens",
  145. "MEU_USUARIO",
  146. "MINHA_SENHA",
  147. {
  148.         host: "localhost",
  149.         dialect: "mysql"
  150. });
  151.  
  152. /*      data e hora     */
  153. var d = new Date();
  154. var B = d.toUTCString();
  155.  
  156. /*       AUTENTICAR NO BANCO DE DADOS           */
  157. sequelize.authenticate().then( () => {
  158.  
  159.         console.log("[" + B + "]: " + "Sucesso ao se conectar ao banco de dados MySQL!");
  160. }).catch(
  161. (erro) => {
  162.                 console.log("[" + B + "]: " + "Erro ao se conectar: " + erro);
  163.  
  164. });
  165.  
  166. module.exports = {
  167.         Sequelize: Sequelize,
  168.         sequelize: sequelize
  169. }
  170.  
  171. /* FIM MODELS */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement