Demo Langsung : Tautan
Lompat ke apa yang baru?
Boilerplate untuk aplikasi web Node.js.
Jika Anda telah menghadiri hackathon di masa lalu, maka Anda tahu berapa banyak waktu yang diperlukan untuk memulai proyek: Tentukan apa yang harus dibangun, pilih bahasa pemrograman, pilih kerangka kerja web, pilih kerangka kerja CSS. Beberapa saat kemudian, Anda mungkin memiliki proyek awal di GitHub, dan hanya dengan begitu anggota tim lain dapat mulai berkontribusi. Atau bagaimana dengan melakukan sesuatu yang sederhana seperti masuk dengan otentikasi Facebook ? Anda dapat menghabiskan waktu berjam -jam jika Anda tidak terbiasa dengan cara kerja OAuth 2.0.
Ketika saya memulai proyek ini, fokus utama saya adalah pada kesederhanaan dan kemudahan penggunaan . Saya juga mencoba menjadikannya generik dan dapat digunakan kembali mungkin untuk mencakup sebagian besar kasus penggunaan aplikasi web hackathon, tanpa terlalu spesifik. Dalam kasus terburuk, Anda dapat menggunakan ini sebagai panduan pembelajaran untuk proyek Anda, jika misalnya Anda hanya tertarik untuk masuk dengan otentikasi Google dan tidak ada yang lain.
“Bagus! Readme itu saja sudah emas!”
- Adrian Le Bas
“Luar biasa. Cukup mengagumkan.”
- Steven Rueter
“Saya menggunakannya selama setahun sekarang dan banyak proyek, ini adalah boilerplate yang luar biasa dan proyek ini terawat dengan baik!”
- Kevin Granger
"Dunia Kecil dengan Proyek Sahat. Kami menggunakan starter hackathon -nya untuk hackathon kami akhir pekan lalu dan mendapat beberapa hadiah. Repo yang sangat berguna!"
- Wawancara kandidat untuk salah satu perusahaan tempat saya bekerja.
MongoDB (instalasi lokal atau di -host)
Node.js 18+
Alat baris perintah
Mac OS X: XCODE (atau OS X 10.9+ : xcode-select --install )
Windows: Visual Studio Code + Windows Subsystem untuk Linux - Ubuntu atau 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
Catatan: Jika Anda baru mengenal Node atau Express, Anda dapat menemukan Node.js & Express dari Scratch Series yang bermanfaat untuk mempelajari dasar -dasar Node dan Express. Atau, berikut adalah tutorial hebat lainnya untuk pemula yang lengkap - memulai dengan Node.js, Express, MongoDB.
Langkah 1: Cara termudah untuk memulai adalah dengan mengkloning repositori:
# 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 Catatan: Saya sangat merekomendasikan menginstal Nodemon. Ini mengawasi setiap perubahan di aplikasi Node.js Anda dan secara otomatis memulai kembali server. Setelah diinstal, alih -alih node app.js gunakan nodemon app.js Ini akan menghemat banyak waktu dalam jangka panjang, karena Anda tidak perlu memulai ulang server secara manual setiap kali Anda membuat perubahan kecil dalam kode. Untuk menginstal, jalankan sudo npm install -g nodemon .
Langkah 2: Dapatkan tombol API dan ubah konfigurasi jika diperlukan setelah menyelesaikan langkah 1 dan secara lokal menginstal MongoDB, Anda harus dapat mengakses aplikasi melalui browser web dan menggunakan akun pengguna lokal. Namun, fungsi tertentu seperti integrasi API mungkin tidak berfungsi dengan benar sampai Anda mendapatkan kunci spesifik dari penyedia layanan. Kunci yang disediakan dalam proyek berfungsi sebagai placeholder, dan Anda dapat mempertahankannya untuk fitur yang saat ini tidak Anda manfaatkan. Untuk memasukkan kunci yang diperoleh ke dalam aplikasi, Anda memiliki dua opsi:
export seperti ini: export FACEBOOK_SECRET=xxxxxx . Metode ini dianggap sebagai praktik yang lebih baik karena mengurangi risiko secara tidak sengaja termasuk rahasia Anda dalam repositori kode..env.example : buka file .env.example dan perbarui kunci placeholder dengan yang baru diakuisisi. Metode ini memiliki risiko check-in rahasia rahasia Anda terhadap repo kode.Apa yang harus didapat dan dikonfigurasi:
SMTP
RECAPTCHA
OAuth untuk login sosial (masuk dengan / login dengan)
Kunci API untuk penyedia layanan dalam contoh API jika Anda berencana menggunakannya.
Atlas Mongodb
Alamat email
NGROK DAN HTTPS Jika Anda ingin menggunakan beberapa API yang membutuhkan HTTP untuk bekerja (misalnya Pinterest atau Facebook), Anda perlu mengunduh NGROK. Mulai Ngrok, atur base_url Anda ke alamat penerusan (yaitu https://3ccb-1234-abcd.ngrok-free.app ), dan gunakan alamat penerusan untuk mengakses aplikasi Anda. Jika Anda menggunakan proxy seperti Ngrok, Anda mungkin mendapatkan kesalahan ketidakcocokan CSRF jika Anda mencoba mengakses aplikasi di http://localhost:8080 alih-alih https: //...ngrok-free.app alamat.
Setelah menginstal atau mengunduh klien Ngrok mandiri, Anda dapat memulai NGROK untuk mencegat data yang dipertukarkan di port 8080 dengan ./ngrok http 8080 di Linux atau ngrok http 8080 di Windows.
Langkah 3: Kembangkan aplikasi Anda dan sesuaikan pengalaman
Langkah 4: Opsional - Deploy ke Produksi Lihat:
Anda perlu mendapatkan kredensial yang sesuai (ID klien, rahasia klien, kunci API, atau nama pengguna & kata sandi) untuk API dan layanan menyediakan yang Anda butuhkan. Lihat Langkah 2 Di bagian Memulai untuk info lebih lanjut.
Dapatkan kredensial SMTP dari penyedia untuk email transaksional. Atur variabel lingkungan SMTP_USER, SMTP_PASSWORD, dan SMTP_HOST. Saat memilih host SMTP, perlu diingat bahwa aplikasi dikonfigurasi untuk menggunakan transmisi SMTP yang aman melalui port 465 di luar kotak. Anda memiliki fleksibilitas untuk memilih penyedia apa pun yang sesuai dengan kebutuhan Anda atau memanfaatkan salah satu penyedia berikut, masing -masing menawarkan tingkat gratis untuk kenyamanan Anda.
| Penyedia | Tier Gratis | Situs web |
|---|---|---|
| Sendgrid | 100 email/hari gratis | https://sendgrid.com |
| Smtp2go | 1000 email/bulan gratis | https://www.smtp2go.com |
| Brevo | 300 email/hari gratis | https://www.brevo.com |
.env . Kunci -kunci ini akan dapat diakses di bawah Pengaturan, Kunci Rekaptcha turun jika Anda membutuhkannya lagi nantihttp://localhost:8080 , dll)http://localhost:8080/auth/google/callback ).envhttp://localhost:8080/auth/snapchat/callback ).env.env.env.envlocalhost di bawah Domain Aplikasihttp://localhost:8080 , dll) di bawah URL situshttp://localhost:8080/auth/facebook/callback ) di bawah oauth redirect uris yang valid Catatan: Setelah masuk yang berhasil dengan Facebook, pengguna akan diarahkan kembali ke halaman beranda dengan hash yang ditambahkan #_=_ di URL. Itu bukan bug. Lihat diskusi Stack Overflow ini untuk cara menanganinya.
http://localhost:8080 , dll) sebagai url beranda.http://localhost:8080/auth/github/callback ).envhttp://localhost:8080 , dll).http://localhost:8080/auth/twitter/callback ).envhttp://localhost:8080/auth/linkedin/callback )http://localhost:8080 , dll).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 Anda | Nama | Keterangan |
|---|---|
| config /passport.js | Paspor Lokal dan OAuth Strategi, ditambah login logam. |
| pengontrol /api.js | Pengontrol untuk rute /API dan semua contoh API. |
| pengontrol /contact.js | Pengontrol untuk formulir kontak. |
| pengontrol /home.js | Pengontrol untuk Home Page (Indeks). |
| Pengontrol /Pengguna.js | Pengontrol untuk manajemen akun pengguna. |
| model /user.js | Skema dan model lumpur untuk pengguna. |
| Publik / | Aset statis (font, CSS, JS, IMG). |
| PUBLIK / JS /Application.js | Tentukan dependensi JavaScript sisi klien. |
| PUBLIK / JS /APP.JS | Tempatkan javascript sisi klien Anda di sini. |
| PUBLIK / CSS / MAIN.SCSS | Stylesheet utama untuk aplikasi Anda. |
| tampilan /akun / | Templat untuk login, reset kata sandi, pendaftaran, profil . |
| Tampilan /API / | Templat untuk contoh API. |
| view /parsials /flash.pug | Kesalahan, info, dan pemberitahuan flash sukses. |
| view /partals /header.pug | Template parsial navbar. |
| view /parsials /footer.pug | Template parsial footer. |
| view /layout.pug | Template dasar. |
| view /home.pug | Template Halaman Beranda. |
| .dockerignore | Folder dan file diabaikan oleh Docker Usage. |
| .env.example | Kunci API Anda, token, kata sandi, dan URI database. |
| .eslintrc | Aturan untuk Eslint Linter. |
| .gitignore | Folder dan file diabaikan oleh git. |
| app.js | File aplikasi utama. |
| Docker-compose.yml | Docker menyusun file konfigurasi. |
| Dockerfile | File Konfigurasi Docker. |
| package.json | Ketergantungan NPM. |
| package-lock.json | Berisi versi yang tepat dari dependensi NPM di package.json. |
CATATAN: Tidak ada preferensi untuk bagaimana Anda memberi nama atau menyusun pandangan Anda. Anda dapat menempatkan semua templat Anda di direktori views tingkat atas tanpa memiliki struktur folder bersarang jika itu membuat segalanya lebih mudah bagi Anda. Jangan lupa untuk memperbarui extends ../layout dan jalur res.render() yang sesuai di pengontrol.
| Kemasan | Keterangan |
|---|---|
| @Fortawesome/Fontawesome-Free | Simbol dan Perpustakaan Ikon. |
| @googleapis/drive | Perpustakaan Integrasi API Google Drive. |
| @googleapis/lembaran | Perpustakaan Integrasi API Google Sheets. |
| @ladjs/bootstrap-sosial | Perpustakaan Tombol Sosial. |
| @LOB/LOB-Typescript-SDK | LOB (USPS Mailing / Layanan Mailing Fisik) Perpustakaan. |
| @node-rs/bcrypt | Perpustakaan untuk Kata Sandi Pengguna Hashing dan Salting. |
| @octokit/istirahat | Perpustakaan API Github. |
| @paspor-js/paspor-twitter | X (Twitter) Dukungan Login (OAuth 2). |
| @Popperjs/Core | Frontend JS Library untuk popper dan tooltips. |
| Axios | Klien HTTP. |
| Parser tubuh | Node.js body parsing middleware. |
| Bootstrap | Kerangka kerja CSS. |
| Chai | Perpustakaan Assersi BDD/TDD. |
| Cheerio | Mengikis halaman web menggunakan sintaks gaya jQuery. |
| kompresi | Node.js Middleware Kompresi. |
| Connect-Mongo | Toko Sesi MongoDB untuk Express. |
| dotenv | Memuat variabel lingkungan dari file .env. |
| errorhandler | Middleware pawang kesalahan khusus pengembangan. |
| Eslint | Linter javascript. |
| ESLINT-Config-AIRBNB-BASE | Konfigurasi Eslint oleh Airbnb. |
| Eslint-plugin-chai-friendly | Membuat Eslint ramah terhadap chai.js 'harapkan' dan 'harus' pernyataan. |
| Eslint-Plugin-Import | Plugin Eslint dengan aturan yang membantu memvalidasi impor yang tepat. |
| cepat | Kerangka kerja web node.js. |
| Express-flash | Memberikan pesan flash untuk Express. |
| Express-rate-limit | Nilai Middleware Membatasi untuk Perlindungan Penyalahgunaan. |
| sesi ekspres | Middleware sesi sederhana untuk Express. |
| serak | Git Hook Manager untuk mengotomatiskan tugas dengan git. |
| jQuery | Perpustakaan JS front-end untuk berinteraksi dengan elemen HTML. |
| lastfm | Perpustakaan API Last.FM. |
| Tahap serapah | Utilitas untuk file serat dipentaskan oleh git. |
| lob | Perpustakaan LOB API. |
| Lodash | Perpustakaan utilitas untuk bekerja dengan array, angka, objek, string. |
| Lusca | Middleware CSRF. |
| Mailchecker | Memverifikasi bahwa alamat email itu valid dan bukan alamat sekali pakai. |
| moka | Kerangka kerja tes. |
| momen | Parse, Validasi, Hitung Tanggal dan Waktu. |
| MongoDBMemoryServer | MongoDB dalam memori (untuk menjalankan tes tanpa menjalankan DB). |
| luwak | MongoDB ODM. |
| Morgan | HTTP Request Logger Middleware untuk Node.js. |
| Multer | Middleware node.js untuk menangani multipart/form-data . |
| nodemailer | Perpustakaan Node.js untuk mengirim email. |
| NYC | Tes cakupan. |
| paspor | Perpustakaan Otentikasi Sederhana dan Elegan untuk Node.js. |
| Buku Paspor-Facebook | Masuk dengan plugin Facebook. |
| paspor-github2 | Masuk dengan plugin GitHub. |
| Paspor-Google-Oauth | Masuk dengan Google Plugin. |
| Paspor-Linkedin-OAuth2 | Masuk dengan plugin LinkedIn. |
| Paspor-Local | Masuk dengan nama pengguna dan plugin kata sandi. |
| Paspor-Oauth | Memungkinkan Anda untuk mengatur strategi OAuth 1.0A dan OAuth 2.0 Anda sendiri. |
| Paspor-OAuth2-Refresh | Perpustakaan untuk menyegarkan token akses oauth 2.0 menggunakan token refresh. |
| Paspor-Snapchat | Masuk dengan plugin Snapchat. |
| Paspor-Steam-Openid | Plugin Steam OpenID 2.0. |
| Paket tambalan | Perbaiki modul simpul yang rusak di depan perbaikan oleh pemelihara. |
| paypal-rest-sdk | Perpustakaan APIS PayPal. |
| Pug | Mesin template untuk ekspres. |
| kelancangan | Sass Compiler untuk menghasilkan CSS dengan kekuatan super |
| Sinon | Tes mata -mata, potongan dan tiruan untuk JavaScript. |
| garis | Perpustakaan API Stripe Offical. |
| supertest | Perpustakaan Assersi HTTP. |
| Twilio | Perpustakaan Twilio API. |
| Twitch-Passport | Masuk dengan plugin Twitch. |
| validator | Perpustakaan validator dan pembersih string. |
filesize(265318); // "265.32 kB" .var token = _.find(req.user.tokens, { kind: 'twitter' }); , di mana parameter pertama adalah array, dan parameter ke -2 adalah objek yang harus dicari. 403 Error: Forbidden saat mengirimkan formulir?Anda perlu menambahkan elemen input tersembunyi berikut ke formulir Anda. Ini telah ditambahkan dalam permintaan tarik #40 sebagai bagian dari perlindungan CSRF.
input(type='hidden', name='_csrf', value=_csrf)
CATATAN: Sekarang dimungkinkan untuk memutar URLS tertentu. Dengan kata lain, Anda dapat menentukan daftar rute yang harus melewati pemeriksaan verifikasi CSRF.
Catatan 2: URL dinamis daftar putih menggunakan tes ekspresi reguler di dalam middleware CSRF untuk melihat apakah req.originalUrl cocok dengan pola yang Anda inginkan.
Itu adalah pesan kesalahan khusus yang ditentukan dalam app.js untuk menunjukkan bahwa ada masalah yang menghubungkan ke 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 ( ) ;
} ) ; Anda harus menjalankan server MongoDB sebelum meluncurkan app.js Anda dapat mengunduh MongoDB di sini, atau menginstalnya melalui manajer paket. Pengguna Windows, Baca Instal MongoDB di Windows.
Kiat: Jika Anda selalu terhubung ke internet, Anda bisa menggunakan MongoDB Atlas alih -alih mengunduh dan menginstal MongoDB secara lokal. Anda hanya perlu memperbarui kredensial basis data di file .env .
Kemungkinan Anda belum mengubah database URI di .env . Jika MONGODB diatur ke localhost , itu hanya akan bekerja pada mesin Anda selama MongoDB berjalan. Saat Anda digunakan untuk merender, OpenShift, atau penyedia lain, Anda tidak akan memiliki MongoDB yang berjalan di localhost . Anda perlu membuat akun dengan mongoDB atlas, lalu membuat database tingkat gratis. Lihat Penempatan untuk informasi lebih lanjut tentang cara mengatur akun dan database baru langkah demi langkah dengan MongoDB Atlas.
Demi kesederhanaan. Meskipun mungkin ada pendekatan yang lebih baik, seperti menyampaikan konteks app ke setiap pengontrol sebagaimana diuraikan dalam blog ini, saya menemukan gaya seperti itu membingungkan bagi pemula. Butuh waktu lama bagi saya untuk memahami konsep exports dan module.exports Exports, apalagi memiliki referensi app global di file lain. Bagi saya adalah berpikir ke belakang. app.js adalah "jantung aplikasi", itu harus menjadi model yang merujuk, rute, pengontrol, dll. Saat bekerja solo pada proyek -proyek kecil, saya lebih suka memiliki semuanya di dalam app.js seperti halnya dengan server API REST ini.
Bagian ini dimaksudkan untuk memberi Anda penjelasan terperinci tentang bagaimana fungsionalitas tertentu bekerja. Mungkin Anda hanya ingin tahu tentang cara kerjanya, atau mungkin Anda tersesat dan bingung saat membaca kode, saya harap ini memberikan beberapa panduan kepada Anda.
HTML5 UP memiliki banyak templat indah yang dapat Anda unduh secara gratis.
Saat Anda mengunduh file zip, itu akan datang dengan index.html , gambar , css dan folder JS . Jadi, bagaimana Anda mengintegrasikannya dengan starter hackathon? Starter Hackathon menggunakan kerangka CSS Bootstrap, tetapi templat ini tidak. Mencoba menggunakan kedua file CSS secara bersamaan kemungkinan akan menghasilkan efek yang tidak diinginkan.
Catatan: Menggunakan pendekatan Templat Kustom, Anda harus memahami bahwa Anda tidak dapat menggunakan kembali tampilan yang saya buat: tata letak, halaman beranda, browser API, login, pendaftaran, manajemen akun, kontak. Pemandangan itu dibangun menggunakan kisi dan gaya bootstrap. Anda harus memperbarui kisi secara manual menggunakan sintaks berbeda yang disediakan dalam templat. Karena itu, Anda dapat mencampur dan mencocokkan jika Anda ingin melakukannya: Gunakan Bootstrap untuk antarmuka aplikasi utama, dan templat khusus untuk halaman arahan.
Mari kita mulai dari awal. Untuk contoh ini saya akan menggunakan Template Velocity Escape:
Catatan: Demi kesederhanaan saya hanya akan mempertimbangkan index.html , dan lewati left-sidebar.html , no-sidebar.html , right-sidebar.html .
Pindahkan semua file JavaScript dari html5up-escape-velocity/js ke public/js . Kemudian pindahkan semua file CSS dari html5up-escape-velocity/css ke public/css . Dan akhirnya, pindahkan semua gambar dari html5up-escape-velocity/images ke public/images . Anda bisa memindahkannya ke folder IMG yang ada, tetapi itu akan membutuhkan perubahan secara manual setiap referensi img . Raih isi index.html dan tempel ke HTML ke Pug.
Catatan: Jangan lupa untuk memperbarui semua jalur CSS dan JS yang sesuai.
Buat file baru escape-velocity.pug dan tempel folder Pug Markup in views . Setiap kali Anda melihat kode res.render('account/login') - itu berarti ia akan mencari views/account/login.pug file.
Mari kita lihat tampilannya. Buat pengontrol baru Escapevelocity Inside controllers/home.js :
exports . escapeVelocity = ( req , res ) => {
res . render ( 'escape-velocity' , {
title : 'Landing Page'
} ) ;
} ; Dan kemudian buat rute di app.js Saya menempatkannya tepat setelah pengontrol indeks:
app . get ( '/escape-velocity' , homeController . escapeVelocity ) ; Restart server (jika Anda tidak menggunakan nodemon ); Maka Anda akan melihat templat baru di http://localhost:8080/escape-velocity
Saya akan berhenti di sini, tetapi jika Anda ingin menggunakan templat ini lebih dari sekadar satu halaman, lihat bagaimana template pug ini bekerja: layout.pug - Template dasar, index.pug - halaman beranda, partials/header.pug - bootstrap navbar, partials/footer.pug - sticky footer. Anda harus memecahnya secara manual menjadi potongan -potongan kecil. Cari tahu bagian mana dari templat yang ingin Anda simpan di semua halaman - itulah layout.pug baru Anda. Kemudian, setiap halaman yang berubah, baik itu index.pug , about.pug , contact.pug akan tertanam dalam layout.pug baru Anda. PUG melalui block content . Gunakan templat yang ada sebagai referensi.
Ini adalah proses yang agak panjang, dan templat yang Anda dapatkan dari tempat lain mungkin memiliki sistem kisi lain. Itu sebabnya saya memilih bootstrap untuk starter hackathon. Banyak orang sudah terbiasa dengan bootstrap , ditambah mudah untuk memulainya jika Anda belum pernah menggunakan bootstrap . Anda juga dapat membeli banyak tema bootstrap yang dirancang dengan indah di ThemeForest, dan menggunakannya sebagai pengganti drop-in untuk starter hackathon. Namun, jika Anda ingin menggunakan desain HTML/CSS yang sepenuhnya khusus, ini akan membantu Anda memulai!
Pesan Flash memungkinkan Anda untuk menampilkan pesan di akhir permintaan dan mengaksesnya pada permintaan berikutnya dan hanya permintaan berikutnya. Misalnya, pada upaya login yang gagal, Anda akan menampilkan peringatan dengan beberapa pesan kesalahan, tetapi segera setelah Anda menyegarkan halaman itu atau mengunjungi halaman yang berbeda dan kembali ke halaman login, pesan kesalahan itu akan hilang. Itu hanya ditampilkan sekali. Proyek ini menggunakan modul ekspres-flash untuk pesan flash. Dan modul itu dibangun di atas connect-flash , yang pada awalnya saya gunakan dalam proyek ini. Dengan Express-Flash Anda tidak perlu secara eksplisit mengirim pesan Flash ke setiap tampilan di dalam res.render() . Semua pesan flash tersedia dalam tampilan Anda melalui objek messages secara default, berkat Express-Flash .
Pesan flash memiliki proses dua langkah. Anda menggunakan req.flash('errors', { msg: 'Error messages goes here' } untuk membuat pesan flash di pengontrol Anda, dan kemudian menampilkannya di tampilan Anda:
if messages . errors
.alert.alert-danger.fade.in
for error in messages . errors
div = error . msg Pada langkah pertama, 'errors' adalah nama pesan flash, yang seharusnya cocok dengan nama properti pada objek messages dalam pandangan Anda. Anda menempatkan pesan peringatan di dalam if message.errors . Alasan mengapa Anda melewati kesalahan seperti { msg: 'Error message goes here' } alih -alih hanya string - 'Error message goes here' , adalah demi konsistensi. Untuk mengklarifikasi itu, modul Express-Validator yang digunakan untuk memvalidasi dan membersihkan input pengguna, mengembalikan semua kesalahan sebagai array objek, di mana setiap objek memiliki properti msg dengan pesan mengapa kesalahan telah terjadi. Berikut adalah contoh yang lebih umum dari apa yang dikembalikan oleh Express-Validator ketika ada kesalahan yang ada:
[
{ param : "name" , msg : "Name is required" , value : "<received input>" } ,
{ param : "email" , msg : "A valid email is required" , value : "<received input>" }
] Agar konsisten dengan gaya itu, Anda harus menyampaikan semua pesan flash sebagai { msg: 'My flash message' } alih -alih string. Jika tidak, Anda akan melihat kotak peringatan tanpa pesan kesalahan. Itu karena di parsial/flash.pug template, ia akan mencoba output error.msg (yaitu "My flash message".msg ), dengan kata lain, ia akan mencoba memanggil metode msg pada objek string , yang akan mengembalikan tidak terdefinisi . Semua yang baru saja saya sebutkan tentang kesalahan, juga berlaku untuk pesan flash "info" dan "sukses", dan Anda bahkan dapat membuat yang baru sendiri, seperti:
Pengontrol penggunaan data (contoh)
req.flash('warning', { msg: 'You have exceeded 90% of your data usage' });
Halaman Akun Pengguna (Contoh)
if messages . warning
.alert.alert-warning.fade.in
for warning in messages . warning
div = warning . msg partials/flash.pug adalah templat parsial yang berisi bagaimana pesan flash diformat. Sebelumnya, pesan flash tersebar di setiap tampilan yang menggunakan pesan flash (kontak, login, pendaftaran, profil), tetapi sekarang, untungnya menggunakan pendekatan kering .
Template parsial pesan flash termasuk dalam layout.pug , bersama dengan footer dan navigasi.
body
include partials/header
.container
include partials/flash
block content
include partials/footerJika Anda memiliki pertanyaan lebih lanjut tentang pesan flash, jangan ragu untuk membuka masalah, dan saya akan memperbarui mini-panduan ini sesuai, atau mengirim permintaan tarik jika Anda ingin memasukkan sesuatu yang saya lewatkan.
A more correct way to say this would be "How do I create a new route?" The main file app.js contains all the routes. 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 . nameItu saja! 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(); dengan kode berikut:
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' ) , ( ) => {ke
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.