Demo en vivo : enlace
Jump a ¿Qué hay de nuevo?
Una placa para aplicaciones web node.js.
Si ha asistido a Hackathons en el pasado, entonces sabe cuánto tiempo lleva comenzar un proyecto: decida qué construir, elija un lenguaje de programación, elija un marco web, elija un marco CSS. Un tiempo después, es posible que tenga un proyecto inicial en Github, y solo entonces otros miembros del equipo pueden comenzar a contribuir. ¿O qué tal hacer algo tan simple como iniciar sesión con la autenticación de Facebook ? Puede pasar horas en él si no está familiarizado con cómo funciona OAuth 2.0.
Cuando comencé este proyecto, mi enfoque principal era la simplicidad y la facilidad de uso . También traté de hacerlo lo más genérico y reutilizable posible para cubrir la mayoría de los casos de uso de aplicaciones web de Hackathon, sin ser demasiado específica. En el peor de los casos, puede usar esto como una guía de aprendizaje para sus proyectos, si por ejemplo solo está interesado en iniciar sesión con la autenticación de Google y nada más.
"¡Bien! ¡Ese lectura solo ya es oro!"
- Adrian Le Bas
"Impresionante. Simplemente increíble".
- Steven Rueter
"Lo estoy usando durante un año y muchos proyectos, ¡es una calderera increíble y el proyecto está bien mantenido!"
- Kevin Granger
"Pequeño mundo con el proyecto de Sahat. Estábamos usando su iniciador de hackathon para nuestro hackathon el pasado fin de semana y obtuvimos algunos premios. ¡Repo realmente práctico!"
- Entrevista candidato para una de las empresas con las que solía trabajar.
MongoDB (instalación local o alojada)
Nodo.js 18+
Herramientas de línea de comandos
Mac OS X: Xcode (o OS X 10.9+ : xcode-select --install )
Windows: Visual Studio Code + Windows Subsystem para Linux - Ubuntu o Visual Studio
Ubuntu / Linux Mint: sudo apt-get install build-essential
Fedora : sudo dnf groupinstall "Development Tools"
OpenSuse: sudo zypper install --type pattern devel_basis
Nota: Si es nuevo en Node o Express, puede encontrar Node.js & Express desde la serie Scratch útil para aprender los conceptos básicos de Node y Express. Alternativamente, aquí hay otro gran tutorial para principiantes completos: comenzar con Node.js, Express, MongoDB.
Paso 1: La forma más fácil de comenzar es clonar el repositorio:
# Get the latest snapshot
git clone https://github.com/sahat/hackathon-starter.git myproject
# Change directory
cd myproject
# Install NPM dependencies
npm install
# Then simply start your app
node app.js Nota: Recomiendo encarecidamente instalar Nodemon. Observa cualquier cambio en su aplicación Node.js y reinicia automáticamente el servidor. Una vez instalado, en lugar de node app.js , use nodemon app.js Le ahorrará mucho tiempo a largo plazo, porque no necesitará reiniciar manualmente el servidor cada vez que realice un pequeño cambio en el código. Para instalar, ejecute sudo npm install -g nodemon .
Paso 2: Obtenga claves API y cambie las configuraciones si es necesario después de completar el Paso 1 e instalar localmente MongoDB, debería poder acceder a la aplicación a través de un navegador web y usar cuentas de usuarios locales. Sin embargo, ciertas funciones como las integraciones de API pueden no funcionar correctamente hasta que obtenga claves específicas de los proveedores de servicios. Las claves proporcionadas en el proyecto sirven como marcadores de posición, y puede retenerlas para las características que no está utilizando actualmente. Para incorporar las claves adquiridas en la aplicación, tiene dos opciones:
export como este: export FACEBOOK_SECRET=xxxxxx . Este método se considera una mejor práctica, ya que reduce el riesgo de incluir accidentalmente sus secretos en un repositorio de código..env.example : abra el archivo .env.example y actualice las claves de marcas de posición con las recién adquiridas. Este método tiene el riesgo de verificar accidentalmente sus secretos a los reposos de código.Qué obtener y configurar:
Smtp
recaptcha
OAuth para inicios de sesión sociales (inicie sesión con / inicie sesión con)
Las claves API para proveedores de servicios en los ejemplos de API si planea usarlos.
MongoDB Atlas
Dirección de correo electrónico
NGROK y HTTPS Si desea utilizar algunas API que necesitan HTTPS para funcionar (por ejemplo, Pinterest o Facebook), deberá descargar NGROK. Inicie NGROK, configure su base_url en la dirección de reenvío (es decir, https://3ccb-1234-abcd.ngrok-free.app libre.app) y use la dirección de reenvío para acceder a su aplicación. Si está utilizando un proxy como NGROK, puede obtener un error de coincidencia CSRF si intenta acceder a la aplicación en http://localhost:8080 en lugar de la dirección https: //...ngrok libre.app.
Después de instalar o descargar el cliente NGROK independiente, puede iniciar NGROK para interceptar los datos intercambiados en el puerto 8080 con ./ngrok http 8080 en Linux o ngrok http 8080 en Windows.
Paso 3: Desarrolle su aplicación y personalice la experiencia
Paso 4: Opcional - Implementación de producción Ver:
Deberá obtener credenciales apropiadas (ID del cliente, secreto del cliente, clave API o nombre de usuario y contraseña) para API y el servicio proporciona que necesita. Consulte el Paso 2 en la sección Getting para obtener más información.
Obtenga credenciales SMTP de un proveedor para correos electrónicos transaccionales. Establezca las variables de entorno SMTP_USER, SMTP_PASSWORD y SMTP_HOST en consecuencia. Al elegir el host SMTP, tenga en cuenta que la aplicación está configurada para usar transmisiones SMTP seguras a través del puerto 465 fuera de la caja. Tiene la flexibilidad de seleccionar cualquier proveedor que se adapte a sus necesidades o aproveche uno de los siguientes proveedores, cada uno ofreciendo un nivel gratuito para su conveniencia.
| Proveedor | Nivel libre | Sitio web |
|---|---|---|
| SendGrid | 100 correos electrónicos/día gratis | https://sendgrid.com |
| SMTP2GO | 1000 correos electrónicos/mes gratis | https://www.smtp2go.com |
| Brevo | 300 correos electrónicos/día gratis | https://www.brevo.com |
.env . Estas claves serán accesibles en configuración, recaptcha teclas desplegable si las necesita nuevamente más tardehttp://localhost:8080 , etc.)http://localhost:8080/auth/google/callback ).envhttp://localhost:8080/auth/snapchat/callback ).env.env.env.envlocalhost en dominios de aplicacioneshttp://localhost:8080 , etc.) bajo URL del sitiohttp://localhost:8080/auth/facebook/callback ) en URIS de redirección de oauth válido Nota: Después de un inicio de sesión exitoso con Facebook, un usuario será redirigido de regreso a la página de inicio con el hash agregado #_=_ en la URL. No es un error. Vea esta discusión de desbordamiento de pila para formas de manejarla.
http://localhost:8080 , etc) como URL de la página de inicio.http://localhost:8080/auth/github/callback ).envhttp://localhost:8080 , etc.).http://localhost:8080/auth/twitter/callback ).envhttp://localhost:8080/auth/linkedin/callback ))http://localhost:8080 , etc.).r_basicprofile.env.env.envhttp://localhost:8080/auth/foursquare/callback ).envhttp://localhost:8080/auth/tumblr/callback ).env.envhttp://localhost:8080/auth/twitch/callback ).env.env.env ..env | Nombre | Descripción |
|---|---|
| config /passport.js | Passport Local y Oauth Strategies, más el middleware de inicio de sesión. |
| controladores /api.js | Controlador para la ruta /API y todos los ejemplos de API. |
| controladores /contact.js | Controlador para el formulario de contacto. |
| Controladores /HOME.JS | Controlador para la página de inicio (índice). |
| controladores /user.js | Controlador para la gestión de la cuenta de usuario. |
| modelos /user.js | Esquema y modelo de mangostos para el usuario. |
| público / | Activos estáticos (fuentes, CSS, JS, IMG). |
| público / js /application.js | Especifique las dependencias de JavaScript del lado del cliente. |
| público / js /app.js | Coloque su JavaScript del lado del cliente aquí. |
| Public / CSS /Main.SCSS | Hojas de estilo principal para su aplicación. |
| Vistas /cuenta / | Plantillas para inicio de sesión, restablecimiento de contraseña, registro, perfil . |
| Vistas /API / | Plantillas para ejemplos de API. |
| vistas /parcials /flash.pug | Error, información y éxito Flash Notificaciones. |
| vistas /parcials /sheader.pug | Plantilla parcial de navbar. |
| vistas /parcials /footer.pug | Plantilla parcial de pie de página. |
| vistas /sayout.pug | Plantilla base. |
| vistas /home.pug | Plantilla de página de inicio. |
| .Dockerignore | Carpeta y archivos ignorados por el uso de Docker. |
| .env.example | Sus claves API, tokens, contraseñas y URI de base de datos. |
| .eslintrc | Reglas para el enlace de Eslint. |
| .gitignore | Carpeta y archivos ignorados por Git. |
| app.js | El archivo de aplicación principal. |
| Docker-composa.yml | Docker componen el archivo de configuración. |
| Dockfile | Archivo de configuración de Docker. |
| paquete.json | Dependencias de NPM. |
| paquete-lock.json | Contiene versiones exactas de las dependencias de NPM en paquete.json. |
Nota: No hay preferencia por cómo nombra o estructura sus vistas. Puede colocar todas sus plantillas en un directorio views de nivel superior sin tener una estructura de carpeta anidada si eso le facilita las cosas. Simplemente no olvide actualizar extends ../layout y las rutas res.render() correspondientes en los controladores.
| Paquete | Descripción |
|---|---|
| @fortawesome/fontawesome-free | Símbolo y biblioteca de iconos. |
| @Googleapis/Drive | Biblioteca de integración de API de Google Drive. |
| @googleapis/sábanas | Biblioteca de integración API de Google Sheets. |
| @ladjs/bootstrap-social | Biblioteca de botones sociales. |
| @lob/lob-typescript-sdk | LOB (Servicio de envío de correo / correo físico de USPS) Biblioteca. |
| @node-rs/bcrypt | Biblioteca para hashing y saltando contraseñas de usuario. |
| @Octokit/Rest | Biblioteca API de GitHub. |
| @Passport-JS/Passport-Twitter | X (Twitter) Soporte de inicio de sesión (OAuth 2). |
| @Popperjs/Core | Frontend JS Biblioteca para poppers y información sobre herramientas. |
| axios | Cliente HTTP. |
| carpeta | Node.js Body analware de análisis. |
| oreja | Marco CSS. |
| chai | Biblioteca de afirmación BDD/TDD. |
| animal | Raspe páginas web con sintaxis de estilo jQuery. |
| compresión | Node.js Compression Middleware. |
| Connect-Mongo | MongoDB Session Store para Express. |
| dotenv | Carga variables de entorno desde el archivo .env. |
| handal | Middleware de controlador de errores de solo desarrollo. |
| eslint | Linter JavaScript. |
| eslint-config-airbnb-base | Configuración eslint por Airbnb. |
| Eslint-plugin-chai-friendly | Hace que Eslint sea amigable con las declaraciones Chai.js 'esperar' y 'debería'. |
| Eslint-Plugin-Import | El complemento de Eslint con reglas que ayudan a validar las importaciones adecuadas. |
| expresar | Marco web node.js. |
| expreso | Proporciona mensajes flash para express. |
| límite de tasas expresas | Tasa que limita el middleware para la protección del abuso. |
| sesión expresa | Middleware de sesión simple para Express. |
| fornido | Git Hook Manager para automatizar las tareas con Git. |
| jQuery | Biblioteca JS front-end para interactuar con elementos HTML. |
| Lastfm | Last.fm API Biblioteca. |
| escenario | Utilidad a archivos de pelusa organizados por Git. |
| lob | Biblioteca de LOB API. |
| lodash | Una biblioteca de utilidad para trabajar con matrices, números, objetos, cadenas. |
| lusca | Middleware CSRF. |
| mailchecker | Verifica que una dirección de correo electrónico sea válida y no una dirección desechable. |
| moca | Marco de prueba. |
| momento | Analizar, validar, calcular fechas y horarios. |
| mongodbmemoryserver | MongoDB en la memoria (para ejecutar pruebas sin un DB en ejecución). |
| mangosta | MongoDB ODM. |
| morgan | HTTP Solicitud Logger Middleware para node.js. |
| muela | Node.js Middleware para manejar multipart/form-data . |
| notailer | Biblioteca Node.js para enviar correos electrónicos. |
| Nueva York | Prueba de cobertura. |
| pasaporte | Biblioteca de autenticación simple y elegante para Node.js. |
| Facebook de pasaporte | Iniciar sesión con el complemento de Facebook. |
| pasaporte-github2 | Iniciar sesión con el complemento GitHub. |
| pasaporte-google-oauth | Iniciar sesión con Google Plugin. |
| pasaporte linkedin-oauth2 | Iniciar sesión con el complemento LinkedIn. |
| pasaporte local | Iniciar sesión con el nombre de usuario y el complemento de contraseña. |
| pasaporte | Le permite configurar sus propias estrategias OAuth 1.0a y Oauth 2.0. |
| Passport-oauth2-fresh | Una biblioteca para actualizar los tokens de acceso OAuth 2.0 usando tokens de actualización. |
| pasaporte-snapchat | Iniciar sesión con el complemento Snapchat. |
| Passport-steam-openid | OpenID 2.0 Plugin de vapor. |
| parche | Arregle los módulos de nodo rotos por delante de las correcciones por parte de los mantenedores. |
| PayPal-Rest-SDK | Biblioteca de API de PayPal. |
| doguillo | Motor de plantilla para express. |
| hablar con descaro a | Compilador SASS para generar CSS con superpoderes |
| sinón | Pruebe espías, trozos y simulacros para JavaScript. |
| raya | Biblioteca API de rayas oficiales. |
| suplente | Biblioteca de afirmación HTTP. |
| twilio | Biblioteca API de Twilio. |
| twitch-passport | Iniciar sesión con el complemento Twitch. |
| validador | Una biblioteca de validadores de cadena y desinfectantes. |
filesize(265318); // "265.32 kB" .var token = _.find(req.user.tokens, { kind: 'twitter' }); , donde el primer parámetro es una matriz, y un segundo parámetro es un objeto a buscar. 403 Error: Forbidden al enviar un formulario?Debe agregar el siguiente elemento de entrada oculta a su formulario. Esto se ha agregado en la solicitud de extracción #40 como parte de la protección CSRF.
input(type='hidden', name='_csrf', value=_csrf)
NOTA: Ahora es posible que la lista blanca sean ciertas URL. En otras palabras, puede especificar una lista de rutas que deben evitar la verificación de verificación CSRF.
Nota 2: Para las URL dinámicas de la lista blanca, use pruebas de expresión regulares dentro del middleware CSRF para ver si req.originalUrl coincide con su patrón deseado.
Ese es un mensaje de error personalizado definido en app.js para indicar que había un problema para conectarse a MongoDB:
mongoose . connection . on ( 'error' , ( err ) => {
console . error ( err ) ;
console . log ( '%s MongoDB connection error. Please make sure MongoDB is running.' , chalk . red ( '✗' ) ) ;
process . exit ( ) ;
} ) ; Debe tener un servidor MongoDB ejecutándose antes de iniciar app.js Puede descargar MongoDB aquí o instalarlo a través de un Administrador de paquetes. Usuarios de Windows, lea Instalar MongoDB en Windows.
Consejo: Si siempre está conectado a Internet, puede usar Atlas MongoDB en lugar de descargar e instalar MongoDB localmente. Solo necesitará actualizar las credenciales de la base de datos en el archivo .env .
Lo más probable es que no haya cambiado la base de datos URI en .env . Si MONGODB está configurado en localhost , solo funcionará en su máquina siempre que MongoDB esté funcionando. Cuando se despliegue para renderizar, OpenShift o algún otro proveedor, no tendrá MongoDB ejecutándose en localhost . Debe crear una cuenta con MongoDB Atlas, luego crear una base de datos de nivel gratuita. Consulte la implementación para obtener más información sobre cómo configurar una cuenta y una nueva base de datos paso a paso con MongoDB Atlas.
En aras de la simplicidad. Si bien puede haber un mejor enfoque, como pasar el contexto app a cada controlador como se describe en este blog, creo que tal estilo es confuso para los principiantes. Me llevó mucho tiempo comprender el concepto de exports y module.exports Exports, y mucho menos tener una referencia app global en otros archivos. Que para mí es un pensamiento atrasado. El app.js es el "corazón de la aplicación", debería ser los modelos, rutas, controladores, etc. de referencia, etc. Al trabajar solo en pequeños proyectos, prefiero tener todo dentro de app.js como es el caso con este servidor API REST.
Esta sección está destinada a darle una explicación detallada de cómo funciona una funcionalidad particular. Tal vez solo tengas curiosidad sobre cómo funciona, o tal vez estás perdido y confundido mientras lees el código, espero que te brinden algo de orientación.
HTML5 UP tiene muchas plantillas hermosas que puede descargar gratis.
Cuando descargue el archivo zip, vendrá con index.html , imágenes , carpetas CSS y JS . Entonces, ¿cómo lo integras con Hackathon Starter? Hackathon Starter usa el marco Bootstrap CSS, pero estas plantillas no. Intentar usar ambos archivos CSS al mismo tiempo probablemente dará como resultado efectos no deseados.
Nota: Usando el enfoque de plantillas personalizadas, debe comprender que no puede reutilizar ninguna de las vistas que he creado: diseño, página de inicio, navegador API, inicio de sesión, registro, administración de cuentas, contacto. Esas vistas se construyeron con cuadrícula y estilos de arranque. Tendrá que actualizar manualmente la cuadrícula utilizando una sintaxis diferente proporcionada en la plantilla. Dicho esto, puede mezclar y combinar si desea hacerlo: use Bootstrap para la interfaz de la aplicación principal y una plantilla personalizada para una página de destino.
Comencemos desde el principio. Para este ejemplo, usaré la plantilla de velocidad de escape:
Nota: En aras de la simplicidad, solo consideraré index.html y omitiré no-sidebar.html right-sidebar.html left-sidebar.html .
Mueva todos los archivos JavaScript de html5up-escape-velocity/js a public/js . Luego mueva todos los archivos CSS de html5up-escape-velocity/css a public/css . Y finalmente, mueva todas las imágenes de html5up-escape-velocity/images a public/images . Puede moverlo a la carpeta IMG existente, pero eso requeriría cambiar manualmente cada referencia img . Tome el contenido de index.html y péguelo en HTML a PUG.
Nota: No olvide actualizar todas las rutas CSS y JS en consecuencia.
Cree un nuevo archivo escape-velocity.pug y pegue el marcado PUG en la carpeta views . Cada vez que ve el código res.render('account/login') , eso significa que buscará el archivo views/account/login.pug .
Veamos cómo se ve. Cree un nuevo controlador de escape Velocity Inside controllers/home.js :
exports . escapeVelocity = ( req , res ) => {
res . render ( 'escape-velocity' , {
title : 'Landing Page'
} ) ;
} ; Y luego cree una ruta en app.js Lo coloqué justo después del controlador de índice:
app . get ( '/escape-velocity' , homeController . escapeVelocity ) ; Reinicie el servidor (si no está usando nodemon ); Entonces debería ver la nueva plantilla en http://localhost:8080/escape-velocity
Me detendré aquí, pero si desea utilizar esta plantilla como más que una sola página, eche un vistazo a cómo funcionan estas plantillas de pug: layout.pug - plantilla base, index.pug - página de inicio, partials/header.pug partials/footer.pug . Tendrás que separarlo manualmente en piezas más pequeñas. Averigüe qué parte de la plantilla desea mantener lo mismo en todas las páginas, esa es su nuevo layout.pug . Luego, cada página que cambia, ya sea index.pug , about.pug , contact.pug se incrustará en su nuevo layout.pug a través block content . Use las plantillas existentes como referencia.
Este es un proceso bastante largo, y las plantillas que obtienes de otros lugares podrían tener otro sistema de cuadrícula. Es por eso que elegí Bootstrap para el iniciador de hackathon. Muchas personas ya están familiarizadas con Bootstrap , además es fácil comenzar con él si nunca ha usado Bootstrap . También puede comprar muchos temas de arranque bellamente diseñados en ThmeForest, y usarlos como un reemplazo de inicio de Hackathon. Sin embargo, si desea ir con un diseño HTML/CSS completamente personalizado, ¡esto debería ayudarlo a comenzar!
Los mensajes flash le permiten mostrar un mensaje al final de la solicitud y acceder a él en la siguiente solicitud y solo la siguiente solicitud. Por ejemplo, en un intento de inicio de sesión fallido, mostraría una alerta con algún mensaje de error, pero tan pronto como actualice esa página o visite una página diferente y regrese a la página de inicio de sesión, ese mensaje de error desaparecerá. Solo se muestra una vez. Este proyecto utiliza el módulo Express-Flash para mensajes flash. Y ese módulo está construido en la parte superior de Connect-Flash , que es lo que utilicé en este proyecto inicialmente. Con Express-Flash no tiene que enviar explícitamente un mensaje flash a cada vista dentro de res.render() . Todos los mensajes flash están disponibles en sus vistas a través del objeto messages de forma predeterminada, gracias a Express-Flash .
Los mensajes flash tienen un proceso de dos pasos. Utiliza req.flash('errors', { msg: 'Error messages goes here' } para crear un mensaje flash en sus controladores y luego mostrarlos en sus vistas:
if messages . errors
.alert.alert-danger.fade.in
for error in messages . errors
div = error . msg En el primer paso, 'errors' es el nombre de un mensaje flash, que debería coincidir con el nombre de la propiedad en el objeto messages en sus vistas. Coloque los mensajes de alerta dentro de if message.errors Porque no desea mostrarles que los mensajes flash estén presentes. La razón por la que pasa un error como { msg: 'Error message goes here' } en lugar de solo una cadena - 'Error message goes here' , es por la consistencia. Para aclarar eso, el módulo expreso-validator que se utiliza para validar y desinfectar la entrada del usuario, devuelve todos los errores como una matriz de objetos, donde cada objeto tiene una propiedad msg con un mensaje por qué ha ocurrido un error. Aquí hay un ejemplo más general de lo que el Validator expreso regresa cuando hay errores presentes:
[
{ param : "name" , msg : "Name is required" , value : "<received input>" } ,
{ param : "email" , msg : "A valid email is required" , value : "<received input>" }
] Para mantenerse consistente con ese estilo, debe pasar todos los mensajes flash como { msg: 'My flash message' } en lugar de una cadena. De lo contrario, verá un cuadro de alerta sin un mensaje de error. Esto se debe a que en la plantilla parcials/flash.pug intentará emitir error.msg (es decir, "My flash message".msg ), en otras palabras, intentará llamar a un método msg en un objeto de cadena , que volverá sin define . Todo lo que acabo de mencionar sobre los errores, también se aplica a los mensajes flash de "información" y "éxito", e incluso podría crear uno nuevo usted mismo, como:
Controlador de uso de datos (ejemplo)
req.flash('warning', { msg: 'You have exceeded 90% of your data usage' });
Página de cuenta de usuario (ejemplo)
if messages . warning
.alert.alert-warning.fade.in
for warning in messages . warning
div = warning . msg partials/flash.pug es una plantilla parcial que contiene cómo se formatean los mensajes flash. Anteriormente, los mensajes flash se dispersaron en cada vista que usaba mensajes flash (contacto, inicio de sesión, registro, perfil), pero ahora, afortunadamente, utiliza un enfoque seco .
La plantilla parcial de mensajes flash se incluye en el layout.pug , junto con los pies de página y la navegación.
body
include partials/header
.container
include partials/flash
block content
include partials/footerSi tiene más preguntas sobre mensajes Flash, no dude en abrir un problema, y actualizaré este mini guía en consecuencia, o enviaré una solicitud de extracción si desea incluir algo que me perdí.
Una forma más correcta de decir esto sería "¿Cómo creo una nueva ruta?" El archivo principal app.js contiene todas las rutas. Cada ruta tiene una función de devolución de llamada asociada con ella. Sometimes you will see three or more arguments for a route. In a case like that, the first argument is still a URL string, while middle arguments are what's called middleware. Think of middleware as a door. If this door prevents you from continuing forward, you won't get to your callback function. One such example is a route that requires authentication.
app . get ( '/account' , passportConfig . isAuthenticated , userController . getAccount ) ; It always goes from left to right. A user visits /account page. Then isAuthenticated middleware checks if you are authenticated:
exports . isAuthenticated = ( req , res , next ) => {
if ( req . isAuthenticated ( ) ) {
return next ( ) ;
}
res . redirect ( '/login' ) ;
} ; If you are authenticated, you let this visitor pass through your "door" by calling return next(); . It then proceeds to the next middleware until it reaches the last argument, which is a callback function that typically renders a template on GET requests or redirects on POST requests. In this case, if you are authenticated, you will be redirected to the Account Management page; otherwise, you will be redirected to the Login page.
exports . getAccount = ( req , res ) => {
res . render ( 'account/profile' , {
title : 'Account Management'
} ) ;
} ; Express.js has app.get , app.post , app.put , app.delete , but for the most part, you will only use the first two HTTP verbs, unless you are building a RESTful API. If you just want to display a page, then use GET , if you are submitting a form, sending a file then use POST .
Here is a typical workflow for adding new routes to your application. Let's say we are building a page that lists all books from the database.
Step 1. Start by defining a route.
app . get ( '/books' , bookController . getBooks ) ;Note: As of Express 4.x you can define your routes like so:
app . route ( '/books' )
. get ( bookController . getBooks )
. post ( bookController . createBooks )
. put ( bookController . updateBooks )
. delete ( bookController . deleteBooks )And here is how a route would look if it required an authentication and an authorization middleware:
app . route ( '/api/twitter' )
. all ( passportConfig . isAuthenticated )
. all ( passportConfig . isAuthorized )
. get ( apiController . getTwitter )
. post ( apiController . postTwitter ) Use whichever style makes sense to you. Either one is acceptable. I think that chaining HTTP verbs on app.route is a very clean and elegant approach, but on the other hand, I can no longer see all my routes at a glance when you have one route per line.
Step 2. Create a new schema and a model Book.js inside the models directory.
const mongoose = require ( 'mongoose' ) ;
const bookSchema = new mongoose . Schema ( {
name : String
} ) ;
const Book = mongoose . model ( 'Book' , bookSchema ) ;
module . exports = Book ; Step 3. Create a new controller file called book.js inside the controllers directory.
/**
* GET /books
* List all books.
*/
const Book = require ( '../models/Book.js' ) ;
exports . getBooks = ( req , res ) => {
Book . find ( ( err , docs ) => {
res . render ( 'books' , { books : docs } ) ;
} ) ;
} ; Step 4. Import that controller in app.js .
const bookController = require ( './controllers/book' ) ; Step 5. Create books.pug template.
extends layout
block content
.page-header
h3 All Books
ul
for book in books
li = book . name¡Eso es todo! I will say that you could have combined Step 1, 2, 3 as following:
app . get ( '/books' , ( req , res ) => {
Book . find ( ( err , docs ) => {
res . render ( 'books' , { books : docs } ) ;
} ) ;
} ) ; Sure, it's simpler, but as soon as you pass 1000 lines of code in app.js it becomes a little challenging to navigate the file. I mean, the whole point of this boilerplate project was to separate concerns, so you could work with your teammates without running into MERGE CONFLICTS . Imagine you have four developers working on a single app.js , I promise you it won't be fun resolving merge conflicts all the time. If you are the only developer, then it's okay. But as I said, once it gets up to a certain LoC size, it becomes difficult to maintain everything in a single file.
That's all there is to it. Express.js is super simple to use. Most of the time you will be dealing with other APIs to do the real work: Mongoose for querying database, socket.io for sending and receiving messages over WebSockets, sending emails via Nodemailer, form validation using validator.js library, parsing websites using Cheerio, etc.
Dan Stroot submitted an excellent pull request that adds a real-time dashboard with socket.io. And as much as I'd like to add it to the project, I think it violates one of the main principles of the Hackathon Starter:
When I started this project, my primary focus was on simplicity and ease of use. I also tried to make it as generic and reusable as possible to cover most use cases of hackathon web apps, without being too specific .
When I need to use socket.io, I really need it, but most of the time - I don't. But more importantly, WebSockets support is still experimental on most hosting providers. Due to past provider issues with WebSockets, I have not include socket.io as part of the Hackathon Starter. For now... If you need to use socket.io in your app, please continue reading.
First, you need to install socket.io:
npm install socket . io Replace const app = express(); Con el siguiente código:
const app = express ( ) ;
const server = require ( 'http' ) . Server ( app ) ;
const io = require ( 'socket.io' ) ( server ) ; I like to have the following code organization in app.js (from top to bottom): module dependencies, import controllers, import configs, connect to database, express configuration, routes, start the server, socket.io stuff. That way I always know where to look for things.
Add the following code at the end of app.js :
io . on ( 'connection' , ( socket ) => {
socket . emit ( 'greet' , { hello : 'Hey there browser!' } ) ;
socket . on ( 'respond' , ( data ) => {
console . log ( data ) ;
} ) ;
socket . on ( 'disconnect' , ( ) => {
console . log ( 'Socket disconnected' ) ;
} ) ;
} ) ;One last thing left to change:
app . listen ( app . get ( 'port' ) , ( ) => {a
server . listen ( app . get ( 'port' ) , ( ) => {At this point, we are done with the back-end.
You now have a choice - to include your JavaScript code in Pug templates or have all your client-side JavaScript in a separate file - in app.js . I admit, when I first started with Node.js and JavaScript in general, I placed all JavaScript code inside templates because I have access to template variables passed in from Express right then and there. It's the easiest thing you can do, but also the least efficient and harder to maintain. Since then I almost never include inline JavaScript inside templates anymore.
But it's also understandable if you want to take the easier road. Most of the time you don't even care about performance during hackathons, you just want to "get shit done" before the time runs out. Well, either way, use whichever approach makes more sense to you. At the end of the day, it's what you build that matters, not how you build it.
If you want to stick all your JavaScript inside templates, then in layout.pug - your main template file, add this to head block.
script ( src = '/socket.io/socket.io.js' )
script .
let socket = io . connect ( window . location . href );
socket . on ( ' greet ' , function ( data ) {
console . log (data);
socket . emit ( ' respond ' , { message : ' Hey there, server! ' });
}); Note: Notice the path of the socket.io.js , you don't actually have to have socket.io.js file anywhere in your project; it will be generated automatically at runtime.
If you want to have JavaScript code separate from templates, move that inline script code into app.js , inside the $(document).ready() function:
$ ( document ) . ready ( function ( ) {
// Place JavaScript code here...
let socket = io . connect ( window . location . href ) ;
socket . on ( 'greet' , function ( data ) {
console . log ( data ) ;
socket . emit ( 'respond' , { message : 'Hey there, server!' } ) ;
} ) ;
} ) ;And we are done!
Declares a read-only named constant.
const name = 'yourName' ;Declares a block scope local variable.
let index = 0 ; Using the `${}` syntax, strings can embed expressions.
const name = 'Oggy' ;
const age = 3 ;
console . log ( `My cat is named ${ name } and is ${ age } years old.` ) ; To import functions, objects, or primitives exported from an external module. These are the most common types of importing.
const name = require ( 'module-name' ) ; const { foo , bar } = require ( 'module-name' ) ;To export functions, objects, or primitives from a given file or module.
module . exports = { myFunction } ; module . exports . name = 'yourName' ; module . exports = myFunctionOrClass ; The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
myFunction ( ... iterableObject ) ; < ChildComponent { ... this . props } /> A Promise is used in asynchronous computations to represent an operation that hasn't completed yet but is expected in the future.
var p = new Promise ( function ( resolve , reject ) { } ) ; The catch() method returns a Promise and deals with rejected cases only.
p . catch ( function ( reason ) { /* handle rejection */ } ) ; The then() method returns a Promise. It takes two arguments: callback for the success & failure cases.
p . then ( function ( value ) { /* handle fulfillment */ } , function ( reason ) { /* handle rejection */ } ) ; The Promise.all(iterable) method returns a promise that resolves when all of the promises in the iterable argument have resolved or rejects with the reason of the first passed promise that rejects.
Promise . all ( [ p1 , p2 , p3 ] ) . then ( function ( values ) { console . log ( values ) } ) ; Arrow function expression. Shorter syntax & lexically binds the this value. Arrow functions are anonymous.
singleParam => { statements } ( ) => { statements } ( param1 , param2 ) => expression const arr = [ 1 , 2 , 3 , 4 , 5 ] ;
const squares = arr . map ( x => x * x ) ; The class declaration creates a new class using prototype-based inheritance.
class Person {
constructor ( name , age , gender ) {
this . name = name ;
this . age = age ;
this . gender = gender ;
}
incrementAge ( ) {
this . age ++ ;
}
}? Credits : DuckDuckGo and @DrkSephy.
? back to top
Math . floor ( Date . now ( ) / 1000 ) ; moment().unix();
var now = new Date ( ) ;
now . setMinutes ( now . getMinutes ( ) + 30 ) ; moment().add(30, 'minutes');
// DD-MM-YYYY
var now = new Date ( ) ;
var DD = now . getDate ( ) ;
var MM = now . getMonth ( ) + 1 ;
var YYYY = now . getFullYear ( ) ;
if ( DD < 10 ) {
DD = '0' + DD ;
}
if ( MM < 10 ) {
MM = '0' + MM ;
}
console . log ( MM + '-' + DD + '-' + YYYY ) ; // 03-30-2016 console.log(moment(new Date(), 'MM-DD-YYYY'));
// hh:mm (12 hour time with am/pm)
var now = new Date ( ) ;
var hours = now . getHours ( ) ;
var minutes = now . getMinutes ( ) ;
var amPm = hours >= 12 ? 'pm' : 'am' ;
hours = hours % 12 ;
hours = hours ? hours : 12 ;
minutes = minutes < 10 ? '0' + minutes : minutes ;
console . log ( hours + ':' + minutes + ' ' + amPm ) ; // 1:43 am console.log(moment(new Date(), 'hh:mm A'));
var today = new Date ( ) ;
var nextWeek = new Date ( today . getTime ( ) + 7 * 24 * 60 * 60 * 1000 ) ; moment().add(7, 'days');
var today = new Date ( ) ;
var yesterday = date . setDate ( date . getDate ( ) - 1 ) ; moment().add(-1, 'days');
? back to top
User . find ( ( err , users ) => {
console . log ( users ) ;
} ) ; let userEmail = '[email protected]' ;
User . findOne ( { email : userEmail } , ( err , user ) => {
console . log ( user ) ;
} ) ; User
. find ( )
. sort ( { _id : - 1 } )
. limit ( 5 )
. exec ( ( err , users ) => {
console . log ( users ) ;
} ) ; Let's suppose that each user has a votes field and you would like to count the total number of votes in your database across all users. One very inefficient way would be to loop through each document and manually accumulate the count. Or you could use MongoDB Aggregation Framework instead:
User . aggregate ( { $group : { _id : null , total : { $sum : '$votes' } } } , ( err , votesCount ) => {
console . log ( votesCount . total ) ;
} ) ;? back to top
You will need to install docker and docker-compose on your system. If you are using WSL, you will need to install Docker Desktop on Windows and docker-compose on WSL.
Docker installation
Common problems setting up docker
After installing docker, start the application with the following commands :
# To build the project while supressing most of the build messages
docker-compose build web
# To build the project without supressing the build messages or using cached data
docker-compose build --no-cache --progress=plain web
# To start the application (or to restart after making changes to the source code)
docker-compose up web
To view the app, find your docker IP address + port 8080 ( this will typically be http://localhost:8080/ ). To use a port other than 8080, you would need to modify the port in app.js, Dockerfile, and docker-compose.yml.
Once you are ready to deploy your app, you will need to create an account with a cloud platform to host it. These are not the only choices, but they are my top picks. Additionally, you can create an account with MongoDB Atlas and then pick one of the providers below. Again, there are plenty of other choices, and you are not limited to just the ones listed below.
Render provides free nodejs hosting for repos on Github and Gitlab.
0.0.0.0/0 . Click SAVE to save the 0.0.0.0/0 whitelist..env.example with this URI string. Make sure to replace the with the db User password that you created under the Security tab.We are deploying your changes . You will need to wait for the deployment to finish before using the DB in your application.sudo gem install rhc ?rhc login and enter your OpenShift credentialsrhc app create MyApp nodejs-0.10git remote add openshift YOUR_GIT_REMOTE Add these two lines to app.js , just place them anywhere before app.listen() :
var IP_ADDRESS = process . env . OPENSHIFT_NODEJS_IP || '127.0.0.1' ;
var PORT = process . env . OPENSHIFT_NODEJS_PORT || 8080 ; Then change app.listen() to:
app . listen ( PORT , IP_ADDRESS , ( ) => {
console . log ( `Express server listening on port ${ PORT } in ${ app . settings . env } mode` ) ;
} ) ; Add this to package.json , after name and version . This is necessary because, by default, OpenShift looks for server.js file. And by specifying supervisor app.js it will automatically restart the server when node.js process crashes.
"main" : "app.js" ,
"scripts" : {
"start" : "supervisor app.js"
} ,git push -f openshift master-f (force) flag because OpenShift creates a dummy server with the welcome page when you create a new Node.js app. Passing -f flag will override everything with your Hackathon Starter project repository. Do not run git pull as it will create unnecessary merge conflicts.git remote add azure [Azure Git URL]git push azure masterNOTE At this point it appears that Bluemix's free tier to host NodeJS apps is limited to 30 days. If you are looking for a free tier service to host your app, Render might be a better choice at this point
Create a Bluemix Account
Sign up for Bluemix, or use an existing account.
Download and install the Cloud Foundry CLI to push your applications to Bluemix.
Create a manifest.yml file in the root of your application.
applications:
- name: <your-app-name>
host: <your-app-host>
memory: 128M
services:
- myMongo-db-name
The host you use will determinate your application URL initially, eg <host>.mybluemix.net . The service name 'myMongo-db-name' is a declaration of your MongoDB service. If you are using other services like Watson for example, then you would declare them the same way.
$ cf login -a https://api.ng.bluemix.net
$ cf create-service mongodb 100 [your-service-name]
Note: this is a free and experiment verion of MongoDB instance. Use the MongoDB by Compose instance for production applications:
$ cf create-service compose-for-mongodb Standard [your-service-name]'
Push the application
$ cf push
$ cf env <your-app-name >
(To view the *environment variables* created for your application)
Done , now go to the staging domain ( <host>.mybluemix.net ) and see your app running.
Be sure to check out the full list of Watson services to forwarder enhance your application functionality with a little effort. Watson services are easy to get going; it is simply a RESTful API call. Here is an example of a Watson Toner Analyzer to understand the emotional context of a piece of text that you send to Watson.
Virtual Assistant - Deliver consistent and intelligent customer care across all channels and touchpoints with conversational AI.
Natural Language Understanding - Analyze text to extract meta-data from content such as concepts, entities, keywords and more.
Discovery - Accelerate business decisions and processes with an AI-powered intelligent document understanding and content analysis platform.
Orchestrate - Hand off tedious tasks to Watson and never work the same way again.
List of Watson Services.
Download and install Node.js
Select or create a Google Cloud Platform Console project
Enable billing for your project (there's a $300 free trial)
Install and initialize the Google Cloud SDK
Create an app.yaml file at the root of your hackathon-starter folder with the following contents:
runtime : nodejs
env : flex
manual_scaling :
instances : 1 Make sure you've set MONGODB_URI in .env.example
Run the following command to deploy the hackathon-starter app:
gcloud app deployMonitor your deployed app in the Cloud Console
View the logs for your app in the Cloud Console
If you are starting with this boilerplate to build an application for prod deployment, or if after your hackathon you would like to get your project hardened for production use, see prod-checklist.md.
You can find the changelog for the project in: CHANGELOG.md
If something is unclear, confusing, or needs to be refactored, please let me know. Pull requests are always welcome, but due to the opinionated nature of this project, I cannot accept every pull request. Please open an issue before submitting a pull request. This project uses Airbnb JavaScript Style Guide with a few minor exceptions. If you are submitting a pull request that involves Pug templates, please make sure you are using spaces , not tabs.
The MIT License (MIT)
Copyright (c) 2014-2023 Sahat Yalkabov
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.