Live -Demo : Link
Springen zu Was ist neu?
Eine Kesselplatte für Node.js -Webanwendungen.
Wenn Sie in der Vergangenheit an Hackathons teilgenommen haben, wissen Sie, wie viel Zeit es braucht, um ein Projekt zu beginnen: Entscheiden Sie, was erstellt, eine Programmiersprache auswählen, ein Web -Framework auswählen und ein CSS -Framework auswählen. Eine Weile später haben Sie möglicherweise ein erstes Projekt auf GitHub und können nur dann andere Teammitglieder mitwirken. Oder wie wäre es, wenn Sie sich bei der Facebook -Authentifizierung so einfach anmelden ? Sie können Stunden damit verbringen, wenn Sie nicht mit der Funktionsweise von OAuth 2.0 vertraut sind.
Als ich dieses Projekt startete, lag mein Hauptfokus auf Einfachheit und Benutzerfreundlichkeit . Ich habe auch versucht, es so generisch und wiederverwendbar wie möglich zu machen, um die meisten Anwendungsfälle von Hackathon -Web -Apps abzudecken, ohne zu spezifisch zu sein. Im schlimmsten Fall können Sie dies als Lernleitfaden für Ihre Projekte verwenden, wenn Sie beispielsweise nur daran interessiert sind , sich bei der Google -Authentifizierung anzumelden , und sonst nichts.
"Schön! Das Lesen allein ist schon Gold!"
- Adrian Le Bas
"Super. Einfach großartig."
- Steven Rueter
"Ich benutze es jetzt seit einem Jahr und vielen Projekten, es ist eine großartige Kesselplatte und das Projekt ist gut gepflegt!"
- Kevin Granger
"Kleine Welt mit Sahats Projekt. Wir haben am vergangenen Wochenende seinen Hackathon -Starter für unseren Hackathon verwendet und einige Preise erhalten. Wirklich praktisches Repo!"
- Befragungskandidat für eines der Unternehmen, mit denen ich früher zusammengearbeitet habe.
MongoDB (lokale Installation oder gehostet)
Node.js 18+
Befehlszeilenwerkzeuge
Mac OS X: Xcode (oder OS X 10.9+ : xcode-select --install )
Windows: Visual Studio Code + Windows -Subsystem für Linux - Ubuntu oder 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
Hinweis: Wenn Sie neu im Knoten oder aus Express sind, finden Sie Node.js & Express From -Scratch -Serie hilfreich, um die Grundlagen von Knoten und Express zu lernen. Alternativ ist hier ein weiteres tolles Tutorial für vollständige Anfänger - erste Unternehmen mit Node.js, Express, MongoDB.
Schritt 1: Der einfachste Weg, um zu beginnen, besteht darin, das Repository zu klonen:
# 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 Hinweis: Ich empfehle dringend, Nodemon zu installieren. Es beobachtet Änderungen in Ihrer Node.js -App und startet den Server automatisch neu. Nach der Installation verwenden Sie anstelle von node app.js nodemon app.js Auf lange Sicht sparen Sie viel Zeit, da Sie den Server nicht jedes Mal manuell neu starten müssen, wenn Sie eine kleine Änderung des Codes vornehmen. Ausführen sudo npm install -g nodemon ausführen.
SCHRITT 2: API -Tasten erhalten und die Konfigurationen bei Bedarf ändern, nachdem Sie Schritt 1 abgeschlossen und mongoDB lokal installiert werden. Sie sollten in der Lage sein, über einen Webbrowser auf die Anwendung zugreifen zu können und lokale Benutzerkonten zu verwenden. Bestimmte Funktionen wie API -Integrationen funktionieren jedoch möglicherweise nicht korrekt, wenn Sie bestimmte Schlüssel von Dienstanbietern erhalten. Die im Projekt bereitgestellten Schlüssel dienen als Platzhalter, und Sie können sie für Funktionen beibehalten, die Sie derzeit nicht verwenden. Um die erworbenen Schlüssel in die Anwendung einzubeziehen, haben Sie zwei Optionen:
export wie folgt verwenden: export FACEBOOK_SECRET=xxxxxx . Diese Methode wird als bessere Praxis angesehen, da sie das Risiko verringert, versehentlich Ihre Geheimnisse in ein Code -Repository aufzunehmen..env.example : Öffnen Sie die Datei .env.example und aktualisieren Sie die Platzhalterschlüssel mit den neu erworbenen. Diese Methode hat das Risiko einer zufälligen Einchecke Ihrer Geheimnisse zu Code-Repos.Was zu bekommen und zu konfigurieren:
SMTP
Recaptcha
OAuth für soziale Anmeldungen (melden Sie sich an / melden Sie sich mit) an)
API -Schlüssel für Dienstleister in den API -Beispielen, wenn Sie sie verwenden möchten.
MongoDb Atlas
E-Mail-Adresse
NGROK und HTTPS Wenn Sie eine API verwenden möchten, die HTTPS benötigt (z. B. Pinterest oder Facebook), müssen Sie NGROK herunterladen. Starten Sie Ngrok, setzen Sie Ihre Base_url auf die Weiterleitungsadresse (dh https://3ccb-1234-abcd.ngrok-free.app ) und verwenden Sie die Weiterleitungsadresse, um auf Ihre Anwendung zuzugreifen. Wenn Sie einen Proxy wie NGROK verwenden, erhalten Sie möglicherweise einen CSRF-Mismatch-Fehler, wenn Sie versuchen, auf die App unter http://localhost:8080 anstelle der Adresse https: //...ngrok-Free.app zugreifen.
Nach dem Installieren oder Herunterladen des eigenständigen NGROK -Clients können Sie NGROK starten, um die auf Port 8080 ausgetauschten Daten mit ./ngrok http 8080 in Linux oder ngrok http 8080 in Windows abzufangen.
Schritt 3: Entwickeln Sie Ihre Anwendung und passen Sie die Erfahrung an
Schritt 4: Optional - Einsatz für die Produktion siehe:
Sie müssen entsprechende Anmeldeinformationen (Client -ID, Client -Geheimnis, API -Schlüssel oder Benutzername und Passwort) für API und Service erhalten, die Sie benötigen. Weitere Informationen finden Sie in Schritt 2 im Abschnitt "Erste Schritte".
Holen Sie sich SMTP -Anmeldeinformationen von einem Anbieter für Transaktions -E -Mails. Setzen Sie die Umgebungsvariablen SMTP_USER, SMTP_PASSWORD und SMTP_HOST entsprechend. Beachten Sie bei der Auswahl des SMTP -Hosts, dass die App so konfiguriert ist, dass sie sichere SMTP -Übertragungen über Port 465 aus der Box verwenden. Sie haben die Flexibilität, einen Anbieter auszuwählen, der Ihren Anforderungen entspricht, oder einen der folgenden Anbieter nutzen, wobei jeweils eine kostenlose Stufe für Ihre Bequemlichkeit angeboten wird.
| Anbieter | Freie Stufe | Webseite |
|---|---|---|
| Sendgrid | 100 E -Mails/Tag kostenlos | https://sendgrid.com |
| SMTP2GO | 1000 E -Mails/Monat kostenlos | https://www.smtp2go.com |
| Brevo | 300 E -Mails/Tag kostenlos | https://www.bervo.com |
.env . Diese Tasten sind unter Einstellungen zugänglich, Recaptcha Keys fällt herunter, wenn Sie sie später erneut benötigenhttp://localhost:8080 usw.)http://localhost:8080/auth/google/callback ).env ein und fügen Sie sie ein und fügen Sie sie einhttp://localhost:8080/auth/snapchat/callback ).env und fügen Sie sie ein und fügen Sie sie ein und fügen Sie sie ein und fügen Sie sie ein.env.env.envlocalhost unter App Domains einhttp://localhost:8080 usw.) unter der URL Sitehttp://localhost:8080/auth/facebook/callback ) unter gültigem OAuth Redirect Uris Hinweis: Nach einer erfolgreichen Anmeldung bei Facebook wird ein Benutzer mit angehängtem Hash #_=_ in der URL zur Startseite umgeleitet. Es ist kein Fehler. In dieser Diskussion zum Stapelüberlauf finden Sie Möglichkeiten, um damit umzugehen.
http://localhost:8080 usw.) als Homepage -URL ein.http://localhost:8080/auth/github/callback ).env -Datei ein und fügen Sie sie einhttp://localhost:8080 usw.).http://localhost:8080/auth/twitter/callback ).env ein und fügen Sie sie einhttp://localhost:8080/auth/linkedin/callback )http://localhost:8080 usw.).r_basicprofile.env -Datei.env -Datei hinzu.env -Datei einfügenhttp://localhost:8080/auth/foursquare/callback ).env -Dateihttp://localhost:8080/auth/tumblr/callback ).env.env -Datei ein und fügen Sie sie einhttp://localhost:8080/auth/twitch/callback ).env ein und fügen Sie sie ein.env.env Datei ein..env -Datei | Name | Beschreibung |
|---|---|
| config /Passport.js | Passport Lokal- und OAuth -Strategien sowie Login Middleware. |
| Controller /api.js | Controller für /API -Route und alle API -Beispiele. |
| Controller /contact.js | Controller für Kontaktformular. |
| Controller /home.js | Controller für die Startseite (Index). |
| Controller /user.js | Controller für Benutzerkontoverwaltung. |
| models /user.js | Mongoose -Schema und Modell für Benutzer. |
| öffentlich / | Statische Vermögenswerte (Schriftarten, CSS, JS, IMG). |
| public / js / Application.js | Geben Sie die clientseitigen JavaScript-Abhängigkeiten an. |
| public / js /app.js | Platzieren Sie hier Ihr clientseitiges JavaScript. |
| public / css /main.scss | Hauptstylesheet für Ihre App. |
| Ansichten /Konto / | Vorlagen für Login, Kennwort zurückgesetzt, Anmeldung, Profil . |
| Ansichten /API / | Vorlagen für API -Beispiele. |
| Ansichten /Partials /flash.pug | Fehler, Info und Erfolg Flash -Benachrichtigungen. |
| Ansichten /Partials /Header.pug | NAVAR -Partialvorlage. |
| Ansichten /Partials /foter.pug | Teilerablage für Fußzeile. |
| Views /layout.pug | Basisvorlage. |
| Ansichten /home.pug | Startseite Vorlage. |
| .Dockerignore | Ordner und Dateien, die durch Docker -Nutzung ignoriert werden. |
| .Env.example | Ihre API -Schlüssel, Token, Passwörter und Datenbank -URI. |
| .eslintrc | Regeln für Eslint -Linter. |
| .Gitignore | Ordner und Dateien von Git ignoriert. |
| app.js | Die Hauptantragsdatei. |
| Docker-compose.yml | Docker -Konfigurationsdatei komponieren. |
| Dockerfile | Docker -Konfigurationsdatei. |
| package.json | NPM -Abhängigkeiten. |
| Package-Lock.json | Enthält genaue Versionen von NPM -Abhängigkeiten in package.json. |
Hinweis: Es gibt keine Präferenz dafür, wie Sie Ihre Ansichten benennen oder strukturieren. Sie können alle Ihre Vorlagen in einem views auf der obersten Ebene aufnehmen, ohne eine verschachtelte Ordnerstruktur zu haben, wenn dies Ihnen die Sache leichter macht. Vergessen Sie einfach nicht res.render() aktualisieren extends ../layout
| Paket | Beschreibung |
|---|---|
| @FortAwesome/fontawesome-frei | Symbol und Symbolbibliothek. |
| @googleapis/Drive | Google Drive API -Integrationsbibliothek. |
| @googleapis/blätter | Google Sheets API -Integrationsbibliothek. |
| @Ladjs/Bootstrap-Social | Bibliothek für soziale Schaltflächen. |
| @LOB/LOB-Typescript-SDK | LOB (USPS Mailing / Physical Mailing Service) Bibliothek. |
| @node-rs/bcrypt | Bibliothek für Hashing- und Salzen von Benutzerkennwörtern. |
| @Octokit/Ruhe | Github API -Bibliothek. |
| @Passport-JS/Passport-Twitter | X (Twitter) Anmeldung (OAuth 2). |
| @popperjs/core | Frontend JS Library für Poppers und Tooltips. |
| Axios | HTTP -Client. |
| Body-Parser | Node.js Körper analysieren Middleware. |
| Bootstrap | CSS -Framework. |
| Chai | BDD/TDD Assertion Library. |
| Cheerio | Kratzen Sie Webseiten mit der Jquery-Syntax. |
| Kompression | Node.js Komprimierung Middleware. |
| Connect-Mongo | MongoDB Session Store für Express. |
| dotenv | Laden Sie Umgebungsvariablen aus .Env -Datei. |
| Fehlerhandler | Nur Entwicklungsfehler-Middleware. |
| Eslint | Linter JavaScript. |
| Eslint-Config-Airbnb-Base | Konfiguration Eslint von Airbnb. |
| Eslint-Plugin-chai-freundlich | Macht eslint freundlich gegenüber chai.js 'erwarten' und 'sollte' Aussagen. |
| Eslint-Plugin-Import | Eslint -Plugin mit Regeln, die dazu beitragen, ordnungsgemäße Importe zu validieren. |
| äußern | Node.js Web Framework. |
| Express-Flash | Bietet Flash -Nachrichten für Express. |
| Express-Rate-Limit | Rate einschränkende Middleware für Missbrauchsschutz. |
| Express-Session | Einfache Sitzung Middleware für Express. |
| heiser | Git Hook Manager, um Aufgaben mit Git zu automatisieren. |
| JQuery | Front-End-JS-Bibliothek, um mit HTML-Elementen zu interagieren. |
| lastfm | Last.fm API -Bibliothek. |
| Fusselstufe | Dienstprogramm für Lint -Dateien von Git inszeniert. |
| Lob | LOB -API -Bibliothek. |
| Lodash | Eine Versorgungsbibliothek für die Arbeit mit Arrays, Zahlen, Objekten, Zeichenfolgen. |
| lusca | CSRF Middleware. |
| Mailchecker | Überprüft, ob eine E -Mail -Adresse gültig ist und keine verfügbare Adresse. |
| Mokka | Testframework. |
| Moment | Analysieren, validieren, Daten und Zeiten berechnen. |
| mongodbmemoryserver | MongoDB im Speicher (zum Ausführen von Tests ohne laufende DB). |
| Mungo | MongoDB ODM. |
| Morgan | HTTP -Anforderung Logger Middleware für node.js. |
| Maultier | Node.js Middleware zum Umgang multipart/form-data . |
| NodeMailer | Node.js Library zum Senden von E -Mails. |
| NYC | Abdeckungstest. |
| Reisepass | Einfache und elegante Authentifizierungsbibliothek für Node.js. |
| Passport-Angepackung | Melden Sie sich mit Facebook Plugin an. |
| Pass-Github2 | Melden Sie sich mit Github-Plugin an. |
| Passport-Google-OAUTH | Melden Sie sich mit Google Plugin an. |
| Pass-Linkedin-OAUTH2 | Melden Sie sich mit LinkedIn Plugin an. |
| Pass-lokal | Melden Sie sich mit Benutzername und Passwort-Plugin an. |
| Passport-oauth | Ermöglicht Ihnen, Ihre eigenen Strategien von OAuth 1.0A und OAuth 2.0 einzurichten. |
| PASSPORT-OAUTH2-REFRESH | Eine Bibliothek zur Aktualisierung von OAuth 2.0 -Zugangsantriebsantrieb mit Aktualisierungstoken. |
| Pass-Snapchat | Melden Sie sich mit Snapchat-Plugin an. |
| Passport-Steam-Openid | OpenID 2.0 Steam Plugin. |
| Patch-Package | Beheben Sie zerbrochene Knotenmodule vor den Korrekturen durch die Betreuer. |
| Paypal-REST-SDK | PayPal APIS -Bibliothek. |
| Mops | Template Engine für Express. |
| Sass | SASS -Compiler, um CSS mit Supermächten zu erzeugen |
| Sinon | Testspione, Stubs und Mocks für JavaScript. |
| Streifen | Offizielle Streifen -API -Bibliothek. |
| Supertest | HTTP Assertion Library. |
| Dämmerung | Twilio API Library. |
| Twitch-Passport | Melden Sie sich mit Twitch Plugin an. |
| Validator | Eine Bibliothek mit String -Validatoren und Desinfektionsmitteln. |
filesize(265318); // "265.32 kB" .var token = _.find(req.user.tokens, { kind: 'twitter' }); , wobei der 1. Parameter ein Array ist und ein 2. Parameter ein Objekt ist, nach dem man suchen muss. 403 Error: Forbidden wenn ich ein Formular einreiche?Sie müssen Ihrem Formular das folgende versteckte Eingangselement hinzufügen. Dies wurde in der Pull -Anfrage #40 als Teil des CSRF -Schutzes hinzugefügt.
input(type='hidden', name='_csrf', value=_csrf)
Hinweis: Es ist jetzt möglich, bestimmte URLs zu Whitelist. Mit anderen Worten, Sie können eine Liste von Routen angeben, die die CSRF -Überprüfungsprüfung umgehen sollten.
ANMERKUNG 2: Dynamische URLs mit Whitelist verwenden regelmäßige Expressionstests in der CSRF -Middleware, um festzustellen, ob req.originalUrl mit Ihrem gewünschten Muster übereinstimmt.
Dies ist eine benutzerdefinierte Fehlermeldung, die in app.js definiert ist, um anzuzeigen, dass ein Problem mit der Verbindung mit MongoDB besteht:
mongoose . connection . on ( 'error' , ( err ) => {
console . error ( err ) ;
console . log ( '%s MongoDB connection error. Please make sure MongoDB is running.' , chalk . red ( '✗' ) ) ;
process . exit ( ) ;
} ) ; Sie benötigen einen MongoDB -Server, der vor dem Start app.js ausgeführt wird. Sie können MongoDB hier herunterladen oder über einen Paketmanager installieren. Windows -Benutzer, Installieren Sie MongoDB unter Windows.
Tipp: Wenn Sie immer mit dem Internet verbunden sind, können Sie nur MongoDB -Atlas verwenden, anstatt MongoDB lokal herunterzuladen und zu installieren. Sie müssen nur Datenbank -Anmeldeinformationen in .env -Datei aktualisieren.
Wahrscheinlich haben Sie die Datenbank URI nicht in .env geändert. Wenn MONGODB auf localhost eingestellt ist, funktioniert es nur auf Ihrer Maschine, solange MongoDB ausgeführt wird. Wenn Sie sich für Rendern, OpenShift oder einen anderen Anbieter einsetzen, werden Sie nicht mit MongoDB auf localhost ausgeführt. Sie müssen ein Konto mit MongoDB -Atlas erstellen und dann eine kostenlose Datenbank erstellen. Weitere Informationen zum Einrichten eines Kontos und einer neuen Datenbank mit MongoDB-Atlas finden Sie in der Bereitstellung.
Aus Einfachheit. Obwohl es einen besseren Ansatz geben könnte, z. B. den in diesem Blog beschriebenen app -Kontext an jeden Controller, finde ich einen solchen Stil, um für Anfänger verwirrend zu sein. Ich habe lange gebraucht, um das Konzept von exports und module.exports zu erfassen, geschweige denn eine globale app -Referenz in anderen Dateien. Das für mich ist rückständig. Das app.js ist das "Herz der App". Es sollte die einzige Referenzierungsmodelle, Routen, Controller usw. sein, wenn ich bei solchen Projekten alleine arbeite, bevorzuge ich alles in app.js , wie es bei diesem REST -API -Server der Fall ist.
Dieser Abschnitt soll Ihnen eine ausführliche Erläuterung geben, wie eine bestimmte Funktionalität funktioniert. Vielleicht sind Sie nur neugierig, wie es funktioniert, oder vielleicht sind Sie verloren und verwirrt, wenn Sie den Code lesen. Ich hoffe, es gibt Ihnen eine Anleitung.
HTML5 UP hat viele schöne Vorlagen, die Sie kostenlos herunterladen können.
Wenn Sie die ZIP -Datei herunterladen, wird sie mit index.html- , Bildern- , CSS- und JS -Ordnern geliefert. Wie integrieren Sie es also in Hackathon -Starter? Hackathon Starter verwendet das Bootstrap CSS -Framework, diese Vorlagen jedoch nicht. Der Versuch, beide CSS -Dateien gleichzeitig zu verwenden, führt wahrscheinlich zu unerwünschten Effekten.
Hinweis: Mit dem Ansatz für benutzerdefinierte Vorlagen sollten Sie verstehen, dass Sie keine der von mir erstellten Ansichten wiederverwenden können: Layout, Homepage, API -Browser, Anmeldung, Anmeldung, Kontoverwaltung, Kontakt. Diese Ansichten wurden mit Bootstrap -Gitter und Stilen erstellt. Sie müssen das Netz manuell mit einer anderen in der Vorlage bereitgestellten Syntax aktualisieren. Trotzdem können Sie sich mischen und übereinstimmen, wenn Sie dies tun möchten: Verwenden Sie Bootstrap für die Haupt -App -Schnittstelle und eine benutzerdefinierte Vorlage für eine Zielseite.
Beginnen wir von vorne. In diesem Beispiel werde ich eine Fluchtgeschwindigkeitsvorlage verwenden:
HINWEIS: Zum Einfachheit halber werde ich nur index.html betrachten und left-sidebar.html , no-sidebar.html , right-sidebar.html überspringen.
Verschieben Sie alle JavaScript-Dateien von html5up-escape-velocity/js nach public/js . Verschieben Sie dann alle CSS-Dateien von html5up-escape-velocity/css in public/css . Und schließlich verschieben Sie alle Bilder von html5up-escape-velocity/images in public/images . Sie könnten es in den vorhandenen IMG -Ordner verschieben, aber das müsste jede img -Referenz manuell ändern. Schnappen Sie sich den Inhalt von index.html und fügen Sie ihn in HTML nach Mope ein.
Hinweis: Vergessen Sie nicht, alle CSS- und JS -Pfade entsprechend zu aktualisieren.
Erstellen Sie eine neue Datei escape-velocity.pug und fügen Sie das Mops-Markup in views ein. Wenn Sie den Code sehen res.render('account/login') - Das heißt, er sucht nach views/account/login.pug -Datei.
Mal sehen, wie es aussieht. Erstellen Sie einen neuen Controller EscapelVeloCity innerhalb von controllers/home.js :
exports . escapeVelocity = ( req , res ) => {
res . render ( 'escape-velocity' , {
title : 'Landing Page'
} ) ;
} ; Und erstellen Sie dann eine Route in app.js Ich habe es direkt nach dem Indexcontroller platziert:
app . get ( '/escape-velocity' , homeController . escapeVelocity ) ; Starten Sie den Server neu (wenn Sie Nodemon nicht verwenden); Dann sollten Sie die neue Vorlage unter http://localhost:8080/escape-velocity sehen
Ich werde hier anhalten, aber wenn Sie diese Vorlage als mehr als nur eine einzelne Seite verwenden möchten, schauen Sie sich an, wie diese Mopsvorlagen funktionieren: layout.pug - Basisvorlage, index.pug - Homepage, partials/header.pug partials/footer.pug Header. Sie müssen es manuell in kleinere Stücke zerlegen. Finden Sie heraus, welchen Teil der Vorlage Sie auf allen Seiten halten möchten - das ist Ihr neues layout.pug . Dann contact.pug jede Seite, die layout.pug about.pug , sei es index.pug block content Verwenden Sie vorhandene Vorlagen als Referenz.
Dies ist ein ziemlich langwieriger Prozess, und Vorlagen, die Sie von anderswo erhalten, haben möglicherweise ein weiteres Netzsystem. Deshalb habe ich mir Bootstrap für den Hackathon -Starter entschieden. Viele Menschen sind bereits mit Bootstrap vertraut, und es ist einfach, damit zu beginnen, wenn Sie noch nie Bootstrap verwendet haben. Sie können auch viele wunderschön gestaltete Bootstrap -Themen bei Themeforest kaufen und sie als Drop-In-Ersatz für Hackathon-Starter verwenden. Wenn Sie jedoch ein vollständig benutzerdefiniertes HTML/CSS -Design entscheiden möchten, sollte dies Ihnen helfen, loszulegen!
Mit Flash -Nachrichten können Sie eine Nachricht am Ende der Anforderung anzeigen und bei der nächsten Anforderung und nur in der nächsten Anfrage darauf zugreifen. Beispielsweise würden Sie bei einem fehlgeschlagenen Anmeldeversuch eine Warnung mit einer Fehlermeldung anzeigen, sobald Sie diese Seite aktualisieren oder eine andere Seite besuchen und zur Anmeldeseite zurückkehren, ist diese Fehlermeldung verschwunden. Es wird nur einmal angezeigt. Dieses Projekt verwendet das Express-Flash- Modul für Flash-Nachrichten. Und dieses Modul ist auf Connect-Flash aufgebaut, was ich in diesem Projekt zunächst verwendet habe. Mit Express-Flash müssen Sie nicht explizit eine Flash-Nachricht an jede Ansicht innerhalb von res.render() senden. Alle Flash-Nachrichten sind dank Express-Flash standardmäßig in Ihren Ansichten über messages verfügbar.
Flash-Nachrichten haben einen zweistufigen Prozess. Sie verwenden req.flash('errors', { msg: 'Error messages goes here' } um eine Flash -Nachricht in deinen Controllern zu erstellen und sie dann in deinen Ansichten anzuzeigen:
if messages . errors
.alert.alert-danger.fade.in
for error in messages . errors
div = error . msg Im ersten Schritt ist 'errors' der Name einer Flash -Nachricht, die mit dem Namen der Eigenschaft in messages in Ihren Ansichten übereinstimmt. Sie platzieren Warnmeldungen in if message.errors da Sie ihnen keine Flash -Nachrichten anzeigen möchten. Der Grund, warum Sie einen Fehler wie { msg: 'Error message goes here' } anstelle einer String übergeben - 'Error message goes here' , ist für die Konsistenz willen. Um dies zu verdeutlichen, gibt das Express-Validator -Modul, das zur Validierung und Bereinigung des Benutzers verwendet wird, alle Fehler als Array von Objekten zurück, wobei jedes Objekt über eine msg Eigenschaft mit einer Nachricht verfügt, warum ein Fehler aufgetreten ist. Hier ist ein allgemeineres Beispiel dafür, was Express-Validator zurückgibt, wenn Fehler vorliegen:
[
{ param : "name" , msg : "Name is required" , value : "<received input>" } ,
{ param : "email" , msg : "A valid email is required" , value : "<received input>" }
] Um mit diesem Stil konsistent zu bleiben, sollten Sie alle Flash -Nachrichten als { msg: 'My flash message' } anstelle einer Zeichenfolge übergeben. Andernfalls sehen Sie ein Warnbox ohne Fehlermeldung. Das liegt daran "My flash message".msg dass in Teillagen/Flash.Pug -Vorlage versucht wird, error.msg msg ausgegeben . Alles, was ich gerade über Fehler erwähnt habe, gilt auch für "Info" und "Erfolg" Flash -Nachrichten, und Sie können sogar selbst eine neue erstellen, wie z. B.:
Datennutzung Controller (Beispiel)
req.flash('warning', { msg: 'You have exceeded 90% of your data usage' });
Seite Benutzerkonto (Beispiel)
if messages . warning
.alert.alert-warning.fade.in
for warning in messages . warning
div = warning . msg partials/flash.pug ist eine teilweise Vorlage, die enthält, wie Flash -Nachrichten formatiert werden. Bisher wurden Flash -Nachrichten in jeder Ansicht verstreut, in der Flash -Nachrichten (Kontakt, Anmeldung, Anmeldung, Profil) verwendet wurden, aber jetzt verwendet es zum Glück einen trockenen Ansatz.
Die teilweise Vorlage von Flash -Nachrichten ist zusammen mit der Fußzeile und der Navigation im layout.pug enthalten .
body
include partials/header
.container
include partials/flash
block content
include partials/footerWenn Sie weitere Fragen zu Flash-Nachrichten haben, öffnen Sie bitte ein Problem. Ich werde diesen Mini-Guide entsprechend aktualisieren oder eine Pull-Anfrage senden, wenn Sie etwas einbeziehen möchten, das ich verpasst habe.
Eine korrektere Art, dies zu sagen, wäre: "Wie erstelle ich eine neue Route?" Die Hauptdatei app.js enthält alle Routen. Each route has a callback function associated with it. 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 . nameDas war's! 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(); mit dem folgenden Code:
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' ) , ( ) => {Zu
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.