العرض التوضيحي الحي : رابط
قفز إلى ما هو جديد؟
غلاية لتطبيقات الويب node.js.
إذا كنت قد حضرت أي hackathons في الماضي ، فأنت تعرف مقدار الوقت الذي يستغرقه بدء المشروع: حدد ما الذي يجب بناءه ، واختيار لغة البرمجة ، أو اختيار إطار عمل ويب ، أو اختيار إطار CSS. بعد فترة من الوقت ، قد يكون لديك مشروع أولي على Github ، وعندها فقط يمكن لأعضاء الفريق الآخرين البدء في المساهمة. أو ماذا عن القيام بشيء بسيط مثل تسجيل الدخول مع مصادقة Facebook ؟ يمكنك قضاء ساعات عليها إذا لم تكن على دراية بكيفية عمل Oauth 2.0.
عندما بدأت هذا المشروع ، كان تركيزي الأساسي على البساطة وسهولة الاستخدام . حاولت أيضًا أن أجعلها عامة وقابلة لإعادة الاستخدام لتغطية معظم حالات استخدام تطبيقات الويب Hackathon ، دون أن تكون محددًا للغاية. في أسوأ الحالات ، يمكنك استخدام هذا كدليل تعليمي لمشاريعك ، إذا كنت مهتمًا على سبيل المثال فقط بتسجيل الدخول مع مصادقة Google ولا شيء آخر.
"جميل! هذا Readme وحده هو الذهب بالفعل!"
- أدريان لو باس
"رائع. ببساطة رائع."
- ستيفن رويتر
"أنا أستخدمه لمدة عام الآن والعديد من المشاريع ، إنه غلاية رائعة ويتم الحفاظ على المشروع جيدًا!"
- كيفن جرانجر
"عالم صغير مع مشروع Sahat. كنا نستخدم بداية Hackathon الخاصة به في Hackathon في نهاية الأسبوع الماضي وحصلوا على بعض الجوائز. ريبو مفيد حقًا!"
- مرشح مقابلة لأحد الشركات التي اعتدت العمل معها.
MongoDB (التثبيت المحلي أو استضافته)
Node.js 18+
أدوات سطر الأوامر
Mac OS X: Xcode (أو OS X 10.9+ : xcode-select --install )
Windows: Visual Studio Code + Windows Subsystem for Linux - Ubuntu أو Visual Studio
Ubuntu / Linux Mint: sudo apt-get install build-essential
فيدورا : sudo dnf groupinstall "Development Tools"
Opensuse: sudo zypper install --type pattern devel_basis
ملاحظة: إذا كنت جديدًا على Node أو Express ، فقد تجد Node.js & Express from Scratch Series مفيدة لتعلم أساسيات العقدة والمعبر. بدلاً من ذلك ، إليك برنامج تعليمي رائع آخر للمبتدئين الكاملين - البدء في Node.js ، Express ، MongoDB.
الخطوة 1: أسهل طريقة للبدء هي استنساخ المستودع:
# 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 ملاحظة: أوصي بشدة بتثبيت Nodemon. إنه يشاهد أي تغييرات في تطبيق Node.js الخاص بك ويعيد تشغيل الخادم تلقائيًا. بمجرد التثبيت ، بدلاً من node app.js استخدم nodemon app.js سيوفر لك الكثير من الوقت على المدى الطويل ، لأنك لن تحتاج إلى إعادة تشغيل الخادم يدويًا في كل مرة تقوم فيها بإجراء تغيير صغير في التعليمات البرمجية. للتثبيت ، قم بتشغيل sudo npm install -g nodemon .
الخطوة 2: الحصول على مفاتيح API وتغيير التكوينات إذا لزم الأمر بعد الانتهاء من الخطوة 1 وتثبيت MongoDB محليًا ، يجب أن تكون قادرًا على الوصول إلى التطبيق من خلال متصفح الويب واستخدام حسابات المستخدم المحلية. ومع ذلك ، قد لا تعمل وظائف معينة مثل تكامل API بشكل صحيح حتى تحصل على مفاتيح محددة من مقدمي الخدمات. تعمل المفاتيح المقدمة في المشروع كعناصر نائبة ، ويمكنك الاحتفاظ بها للحصول على ميزات لا تستخدمها حاليًا. لدمج المفاتيح المكتسبة في التطبيق ، لديك خياران:
export مثل هذا: export FACEBOOK_SECRET=xxxxxx . تعتبر هذه الطريقة ممارسة أفضل لأنها تقلل من خطر الإصابة بالصدفة بما في ذلك الأسرار في مستودع التعليمات البرمجية..env.example : افتح ملف .env.example وقم بتحديث مفاتيح العنصر النائب مع المفاتيح المكتسبة حديثًا. تحتوي هذه الطريقة على خطر الاختبار العرضي لأسرارك إلى إعادة الشفرة.ماذا تحصل وتكوين:
SMTP
recaptcha
OAUTH للتسجيلات الاجتماعية (تسجيل الدخول مع / تسجيل الدخول مع)
مفاتيح API لمقدمي الخدمات في أمثلة API إذا كنت تخطط لاستخدامها.
Mongodb أطلس
عنوان البريد الإلكتروني
NGROK و HTTPS إذا كنت ترغب في استخدام بعض واجهة برمجة التطبيقات التي تحتاج إلى HTTPS للعمل (على سبيل المثال Pinterest أو Facebook) ، ستحتاج إلى تنزيل NGROK. ابدأ NGROK ، قم بتعيين BASE_URL على عنوان إعادة التوجيه (أي https://3ccb-1234-abcd.ngrok-free.app ) ، واستخدم عنوان إعادة التوجيه للوصول إلى التطبيق الخاص بك. إذا كنت تستخدم وكيلًا مثل NGROK ، فقد تحصل على خطأ غير متطابق في CSRF إذا حاولت الوصول إلى التطبيق على http://localhost:8080 بدلاً من عنوان https: //...ngrok-free.app.
بعد تثبيت أو تنزيل عميل NGROK المستقل ngrok http 8080 يمكنك بدء تشغيل NGROK لاعتراض البيانات التي تم تبادلها على المنفذ ./ngrok http 8080 مع.
الخطوة 3: تطوير التطبيق الخاص بك وتخصيص التجربة
الخطوة 4: اختياري - نشر على الإنتاج راجع:
ستحتاج إلى الحصول على بيانات الاعتماد المناسبة (معرف العميل أو سر العميل أو مفتاح واجهة برمجة التطبيقات أو اسم المستخدم وكلمة المرور) لواجهة برمجة التطبيقات وخدمة الخدمة التي تحتاجها. انظر الخطوة 2 في قسم البدء لمزيد من المعلومات.
الحصول على بيانات اعتماد SMTP من مزود لرسائل البريد الإلكتروني للمعاملات. قم بتعيين متغيرات البيئة SMTP_USER و SMTP_PASSWORD و SMTP_HOST وفقًا لذلك. عند اختيار مضيف SMTP ، ضع في اعتبارك أن التطبيق تم تكوينه لاستخدام عمليات نقل SMTP الآمنة عبر المنفذ 465 خارج المربع. لديك المرونة لتحديد أي مزود يناسب احتياجاتك أو الاستفادة من أحد مقدمي الخدمات التالية ، كل منهم يقدم طبقة مجانية لراحتك.
| مزود | طبقة مجانية | موقع إلكتروني |
|---|---|---|
| SendGrid | 100 رسالة بريد إلكتروني/يوم مجانًا | https://sendgrid.com |
| SMTP2GO | 1000 رسالة بريد إلكتروني/شهر مجانًا | https://www.smtp2go.com |
| بريفو | 300 رسالة بريد إلكتروني/يوم مجانًا | https://www.brevo.com |
.env . يمكن الوصول إلى هذه المفاتيح ضمن الإعدادات ، و recaptcha مفاتيح المنسدلة إذا كنت بحاجة إليها مرة أخرى لاحقًاhttp://localhost:8080 ، إلخ)http://localhost:8080/auth/google/callback ).envhttp://localhost:8080/auth/snapchat/callback ).env.env.env.envlocalhost ضمن مجالات التطبيقhttp://localhost:8080 ، etc) ضمن عنوان URL للموقعhttp://localhost:8080/auth/facebook/callback ملاحظة: بعد تسجيل دخول ناجح مع Facebook ، سيتم إعادة توجيه المستخدم إلى الصفحة الرئيسية مع التجزئة المرسلة #_=_ في عنوان URL. انها ليست خطأ. شاهد مناقشة فائض في التدفق هذه للحصول على طرق للتعامل معها.
http://localhost:8080 ، etc) باعتباره عنوان URL للصفحة الرئيسية.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 ، إلخ).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 الخاص بك | اسم | وصف |
|---|---|
| config /passport.js | Passport Local و Oauth استراتيجيات ، بالإضافة إلى تسجيل الدخول إلى البرامج الوسيطة. |
| وحدات التحكم /api.js | وحدة التحكم في /API Route وجميع أمثلة API. |
| وحدات التحكم /contact.js | وحدة التحكم في نموذج الاتصال. |
| وحدات التحكم /home.js | وحدة تحكم الصفحة الرئيسية (الفهرس). |
| وحدات التحكم /user.js | وحدة تحكم لإدارة حساب المستخدم. |
| النماذج /وسر | مخطط mongoose ونموذج المستخدم. |
| عام / | الأصول الثابتة (الخطوط ، CSS ، JS ، IMG). |
| الجمهور / JS /Application.js | حدد تبعيات JavaScript من جانب العميل. |
| عام / JS / app.js | ضع JavaScript من جانب العميل هنا. |
| عام / css /main.scss | ورقة الأنماط الرئيسية لتطبيقك. |
| طرق العرض /الحساب / | قوالب لتسجيل الدخول ، إعادة تعيين كلمة المرور ، الاشتراك ، الملف الشخصي . |
| وجهات النظر /API / | قوالب لأمثلة API. |
| وجهات النظر /partials /flash.pug | الخطأ والمعلومات وإخطارات فلاش النجاح. |
| وجهات النظر /الجزئية /header.pug | قالب NAVBAR الجزئي. |
| وجهات النظر /partials /footer.pug | القالب الجزئي تذييل. |
| وجهات النظر /llayout.pug | قالب قاعدة. |
| وجهات النظر /home.pug | قالب الصفحة الرئيسية. |
| .Dockerignore | المجلد والملفات التي تم تجاهلها عن طريق استخدام Docker. |
| .env.example | مفاتيح API الخاصة بك ، الرموز الرموز ، كلمات المرور وقاعدة البيانات URI. |
| .eslintrc | قواعد eslint linter. |
| .gitignore | المجلد والملفات التي تجاهلها GIT. |
| app.js | ملف التطبيق الرئيسي. |
| Docker-corm.yml | Docker تكوين ملف التكوين. |
| Dockerfile | ملف تكوين Docker. |
| package.json | التبعيات NPM. |
| حزمة lock.json | يحتوي على إصدارات دقيقة من التبعيات NPM في package.json. |
ملاحظة: لا يوجد تفضيل لكيفية تسمية أو هيكل وجهات نظرك. يمكنك وضع جميع القوالب الخاصة بك في دليل views المستوى الأعلى دون أن يكون لديك هيكل مجلد متداخل إذا كان ذلك يجعل الأمور أسهل بالنسبة لك. فقط لا تنس أن تحديث extends ../layout ومسارات res.render() المقابلة في وحدات التحكم.
| طَرد | وصف |
|---|---|
| @Fortawesome/Fontawesome | رمز ومكتبة أيقونة. |
| @googleapis/محرك | مكتبة تكامل API Google Drive. |
| @Googleapis/Sheets | مكتبة تكامل API Google Sheets. |
| @ladjs/bootstrap-social | مكتبة الأزرار الاجتماعية. |
| @lob/lob-typescript-sdk | مكتبة LOB (USPS البريدية / الخدمة المادية). |
| @node-rs/bcrypt | مكتبة لجامع كلمات مرور مستخدم التجزئة والتمليخ. |
| @Octokit/REST | مكتبة Github API. |
| @Passport-JS/Passport-Twitter | X (Twitter) دعم تسجيل الدخول (OAuth 2). |
| @popperjs/core | مكتبة Frontend JS لبوسق وتلميذات الأدوات. |
| البديهية | عميل HTTP. |
| جسم الجسد | node.js الجسم تحليل الوسيطة. |
| bootstrap | إطار CSS. |
| تشاي | مكتبة تأكيد BDD/TDD. |
| Cheerio | كشط صفحات الويب باستخدام بناء الجملة على غرار jQuery. |
| ضغط | Node.js ضغط الوسيطة. |
| توصيل مونغو | متجر جلسة MongoDB لـ Express. |
| dotenv | يحمل متغيرات البيئة من ملف .env. |
| errorHandler | التطوير فقط خطأ معالج الوسيطة. |
| eslint | لينتر جافا سكريبت. |
| ESLINT-CONFIG-AIRBNB-base | تكوين ESLINT بواسطة Airbnb. |
| Eslint-plugin-chai الصديق | يجعل ESLINT صديقًا لكي تشاي. |
| Eslint-plugin-import | ESLINT البرنامج المساعد مع القواعد التي تساعد على التحقق من الواردات المناسبة. |
| يعبر | Node.js إطار الويب. |
| صريح | يوفر رسائل فلاش لـ Express. |
| صريح المعدل | معدل الحد من الوسيطة لحماية الإساءة. |
| جلسة صريحة | الوسيطة الجلسة البسيطة لـ Express. |
| أجش | GIT Hook Manager لأتمتة المهام مع GIT. |
| jQuery | مكتبة JS في الواجهة الأمامية للتفاعل مع عناصر HTML. |
| LASTFM | Last.FM API Library. |
| الوبر | فائدة للملفات الوبر التي تم عرضها بواسطة GIT. |
| رفع الكرة | LOB API Library. |
| لوداش | مكتبة فائدة للعمل مع المصفوفات والأرقام والكائنات والسلاسل. |
| Lusca | CSRF الوسيطة. |
| MailChecker | يتحقق من أن عنوان البريد الإلكتروني صالح وليس عنوانًا يمكن التخلص منه. |
| موكا | إطار اختبار. |
| لحظة | تحليل ، التحقق من صحة ، حساب التواريخ والأوقات. |
| MongoDbMemoryServer | mongoDB في الذاكرة (للاختبارات تشغيل دون تشغيل DB). |
| النمس | Mongodb ODM. |
| مورغان | HTTP طلب المسجل الأوساط ل Node.js. |
| مولتر | node.js الوسيطة للتعامل مع multipart/form-data . |
| Nodemailer | مكتبة Node.js لإرسال رسائل البريد الإلكتروني. |
| مدينة نيويورك | اختبار التغطية. |
| جواز سفر | مكتبة مصادقة بسيطة وأنيقة لـ Node.js. |
| Passport-Facebook | تسجيل الدخول مع المكون الإضافي على Facebook. |
| جواز السفر github2 | تسجيل الدخول مع البرنامج المساعد github. |
| جواز السفر-جوغل أولا | تسجيل الدخول مع Plugin Google. |
| جواز سفر-رينكيدن-OAUTH2 | تسجيل الدخول مع المكون الإضافي LinkedIn. |
| جواز السفر المحلي | تسجيل الدخول مع اسم المستخدم وكلمة المرور المكوّن الإضافي. |
| جواز السفر | يسمح لك بإعداد استراتيجيات OAUTH 1.0A و OAUTH 2.0. |
| Passport-OAuth2-REFRESH | مكتبة لتحديث رموز الوصول إلى Oauth 2.0 باستخدام الرموز المميزة للتحديث. |
| جواز سفر SNAPCHAT | تسجيل الدخول مع البرنامج المساعد Snapchat. |
| جواز سفر-دونييد | OpenID 2.0 Steam Plugin. |
| حزمة التصحيح | إصلاح وحدات العقدة المكسورة قبل الإصلاحات من قبل المشرفين. |
| paypal-rest-sdk | مكتبة واجهات برمجة التطبيقات PayPal. |
| الصلصال | محرك قالب لـ Express. |
| ساس | برنامج التحويل البرمجي Sass لتوليد CSS مع القوى العظمى |
| سنون | اختبار الجواسيس ، رعب وتهديدات لجافا سكريبت. |
| شريط | مكتبة واجهة برمجة تطبيقات الشريط الخارجة. |
| اختبار العواري | مكتبة تأكيد HTTP. |
| twilio | مكتبة Twilio API. |
| Twitch-Passport | تسجيل الدخول مع Twitch Plugin. |
| المدقق | مكتبة من صحة السلسلة والمعقات. |
filesize(265318); // "265.32 kB" .var token = _.find(req.user.tokens, { kind: 'twitter' }); ، حيث تكون المعلمة الأولى عبارة عن صفيف ، والمعلمة الثانية هي كائن للبحث عنه. 403 Error: Forbidden عند إرسال نموذج؟تحتاج إلى إضافة عنصر الإدخال المخفي التالي إلى النموذج الخاص بك. تمت إضافة هذا في طلب السحب رقم 40 كجزء من حماية CSRF.
input(type='hidden', name='_csrf', value=_csrf)
ملاحظة: أصبح من الممكن الآن أن تقوم بعنوان URL ببعض عناوين URL. بمعنى آخر ، يمكنك تحديد قائمة من الطرق التي يجب أن تتجاوز فحص التحقق من CSRF.
ملاحظة 2: بالنسبة إلى عناوين URL الديناميكية ذات القائمة البيضاء ، استخدم اختبارات التعبير العادية داخل الوسيطة الوسيطة CSRF لمعرفة ما إذا كان req.originalUrl يطابق النمط المطلوب.
هذه رسالة خطأ مخصصة محددة في app.js للإشارة إلى أن هناك مشكلة في الاتصال بـ 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 ( ) ;
} ) ; تحتاج إلى تشغيل خادم MongoDB قبل بدء تشغيل app.js يمكنك تنزيل MongoDB هنا ، أو تثبيته عبر مدير الحزمة. مستخدمي Windows ، اقرأ تثبيت mongodb على Windows.
نصيحة: إذا كنت متصلاً دائمًا بالإنترنت ، فيمكنك فقط استخدام MongoDB Atlas بدلاً من تنزيل وتثبيت MongoDB محليًا. ستحتاج فقط إلى تحديث بيانات اعتماد قاعدة البيانات في ملف .env .
من المحتمل أنك لم تغير قاعدة البيانات URI في .env . إذا تم ضبط MONGODB على localhost ، فسيعمل فقط على جهازك طالما يتم تشغيل MongoDB. عند نشرها لتقديمها أو OpenShift أو موفر آخر ، لن يكون لديك MongoDB يعمل على localhost . تحتاج إلى إنشاء حساب مع MongoDB Atlas ، ثم إنشاء قاعدة بيانات المستوى المجانية. راجع النشر لمزيد من المعلومات حول كيفية إعداد حساب وقاعدة بيانات جديدة خطوة بخطوة مع MongoDB Atlas.
من أجل البساطة. على الرغم من أنه قد يكون هناك نهج أفضل ، مثل تمرير سياق app إلى كل وحدة تحكم كما هو موضح في هذه المدونة ، أجد أن هذا الأسلوب يربك للمبتدئين. استغرق الأمر وقتًا app لفهم مفهوم exports والوحدة module.exports . ثا بالنسبة لي هو التفكير المتخلف. app.js هو "قلب التطبيق" ، يجب أن يكون النماذج التي تشير إلى النماذج والطرق ووحدات التحكم ، وما إلى ذلك. عند العمل الفردي في مشاريع صغيرة ، أفضل أن يكون لدي كل شيء داخل app.js كما هو الحال مع خادم API Rest هذا.
هذا القسم مخصص لإعطائك شرحًا مفصلاً لكيفية عمل وظيفة معينة. ربما تكون فضوليًا بشأن كيفية عمله ، أو ربما تضيع وترتبك أثناء قراءة الكود ، آمل أن يوفر لك بعض التوجيهات.
يحتوي HTML5 UP على العديد من القوالب الجميلة التي يمكنك تنزيلها مجانًا.
عند تنزيل ملف zip ، سيأتي مع index.html ، الصور ، CSS و JS المجلدات. لذا ، كيف تدمجها مع بداية Hackathon؟ يستخدم Hackathon Starter إطار Bootstrap CSS ، ولكن هذه القوالب لا. من المحتمل أن تؤدي محاولة استخدام كلا ملفات CSS في نفس الوقت إلى تأثيرات غير مرغوب فيها.
ملاحظة: باستخدام نهج القوالب المخصصة ، يجب أن تفهم أنه لا يمكنك إعادة استخدام أي من المشاهدات التي قمت بإنشائها: التخطيط ، الصفحة الرئيسية ، متصفح واجهة برمجة التطبيقات ، تسجيل الدخول ، التسجيل ، إدارة الحساب ، جهة الاتصال. تم بناء تلك الآراء باستخدام شبكة bootstrap والأنماط. سيتعين عليك تحديث الشبكة يدويًا باستخدام بناء جملة مختلف متوفر في القالب. بعد قولي هذا ، يمكنك المزج والمطابقة إذا كنت تريد القيام بذلك: استخدم Bootstrap لواجهة التطبيق الرئيسية ، وقالب مخصص لصفحة مقصودة.
لنبدأ من البداية. في هذا المثال ، سأستخدم قالب سرعة الهروب:
ملاحظة: من أجل البساطة ، سأدرس فقط index.html ، وتخطي left-sidebar.html ، no-sidebar.html ، right-sidebar.html .
انقل جميع ملفات JavaScript من html5up-escape-velocity/js إلى public/js . ثم انقل جميع ملفات CSS من html5up-escape-velocity/css إلى public/css . وأخيرًا ، انقل جميع الصور من html5up-escape-velocity/images إلى public/images . يمكنك نقله إلى مجلد IMG الحالي ، لكن هذا يتطلب تغيير كل مرجع img يدويًا. الاستيلاء على محتويات index.html والصقه في html إلى pug.
ملاحظة: لا تنسَ تحديث جميع مسارات CSS و JS وفقًا لذلك.
قم views ملف جديد escape-velocity.pug . كلما رأيت رمز res.render('account/login') - هذا يعني أنه سيبحث عن ملفات views/account/login.pug .
دعونا نرى كيف تبدو. قم بإنشاء وحدة تحكم جديدة EscapeVelocity داخل controllers/home.js :
exports . escapeVelocity = ( req , res ) => {
res . render ( 'escape-velocity' , {
title : 'Landing Page'
} ) ;
} ; ثم إنشاء مسار في app.js لقد وضعته مباشرة بعد وحدة تحكم الفهرس:
app . get ( '/escape-velocity' , homeController . escapeVelocity ) ; أعد تشغيل الخادم (إذا كنت لا تستخدم Nodemon ) ؛ ثم يجب أن ترى القالب الجديد في http://localhost:8080/escape-velocity
سأتوقف هنا ، ولكن إذا كنت ترغب في استخدام هذا القالب كأكثر من index.pug صفحة واحدة ، ألقِ نظرة على كيفية عمل قوالب الصلصال partials/footer.pug : layout.pug partials/header.pug سيكون عليك تفكيكها يدويًا إلى قطع أصغر. اكتشف أي جزء من القالب الذي تريد الاحتفاظ به على جميع الصفحات - هذا هو layout.pug الجديد. block content ذلك ، layout.pug صفحة تتغير ، سواء كان ذلك index.pug ، about.pug contact.pug استخدم القوالب الموجودة كمرجع.
هذه عملية طويلة إلى حد ما ، وقد تحتوي القوالب التي تحصل عليها من مكان آخر على نظام شبكة آخر. لهذا السبب اخترت Bootstrap لبداية Hackathon. كثير من الناس على دراية بالفعل بالتمهيد ، بالإضافة إلى أنه من السهل البدء به إذا لم تستخدم أبدًا Bootstrap . يمكنك أيضًا شراء العديد من سمات bootstrap المصممة بشكل جميل في TheMeForest ، واستخدامها كبديل للبدء في Hackathon Starter. ومع ذلك ، إذا كنت ترغب في الذهاب بتصميم HTML/CSS مخصص تمامًا ، فيجب أن يساعدك ذلك في البدء!
تتيح لك رسائل الفلاش عرض رسالة في نهاية الطلب والوصول إليها في الطلب التالي والطلب التالي فقط. على سبيل المثال ، في محاولة تسجيل الدخول الفاشلة ، ستعرض تنبيهًا مع بعض رسائل الخطأ ، ولكن بمجرد تحديث هذه الصفحة أو زيارة صفحة مختلفة والعودة إلى صفحة تسجيل الدخول ، ستختفي رسالة الخطأ هذه. يتم عرضه مرة واحدة فقط. يستخدم هذا المشروع الوحدة النمطية السريعة لرسائل الفلاش. وقد تم تصميم هذه الوحدة على رأس Connect-Flash ، وهو ما استخدمته في هذا المشروع في البداية. مع الفلاش السريع ، لا يتعين عليك إرسال رسالة فلاش بشكل صريح إلى كل عرض داخل res.render() . تتوفر جميع رسائل الفلاش في مشاهداتك عبر كائن messages افتراضيًا ، وذلك بفضل Express-Flash .
رسائل الفلاش لها عملية من خطوتين. يمكنك استخدام req.flash('errors', { msg: 'Error messages goes here' } لإنشاء رسالة فلاش في وحدات التحكم الخاصة بك ، ثم عرضها في طرق العرض الخاصة بك:
if messages . errors
.alert.alert-danger.fade.in
for error in messages . errors
div = error . msg في الخطوة الأولى ، 'errors' هو اسم رسالة فلاش ، والتي يجب أن تتطابق مع اسم الخاصية على كائن messages في طرق العرض الخاصة بك. يمكنك وضع رسائل تنبيه في الداخل if message.errors لأنك لا ترغب في إظهار رسائل الفلاش لها. السبب في أنك تمرير خطأ مثل { msg: 'Error message goes here' } بدلاً من مجرد سلسلة - 'Error message goes here' ، من أجل الاتساق. لتوضيح ذلك ، تُرجع الوحدة النمطية السريعة للمخططات التي يتم استخدامها للتحقق من إدخال المستخدم وتطهيرها ، جميع الأخطاء كمجموعة من الكائنات ، حيث يحتوي كل كائن على خاصية msg مع رسالة لماذا حدث خطأ. فيما يلي مثال أكثر عمومية على ما يعوده الفراشات السريعة عند وجود أخطاء:
[
{ param : "name" , msg : "Name is required" , value : "<received input>" } ,
{ param : "email" , msg : "A valid email is required" , value : "<received input>" }
] للاحتفاظ بما يتوافق مع هذا النمط ، يجب عليك تمرير جميع رسائل الفلاش مثل { msg: 'My flash message' } بدلاً من سلسلة. خلاف ذلك ، سترى مربع تنبيه بدون رسالة خطأ. ذلك لأنه في قالب /flash.pug ، سيحاول إخراج error.msg msg (أي "My flash message".msg ) ، وبعبارة أخرى ، سيحاول استدعاء طريقة msg على كائن سلسلة ، والتي ستعود غير محددة . كل ما ذكرته للتو حول الأخطاء ، ينطبق أيضًا على رسائل "المعلومات" و "النجاح" ، ويمكنك حتى إنشاء واحدة جديدة بنفسك ، مثل:
وحدة تحكم استخدام البيانات (مثال)
req.flash('warning', { msg: 'You have exceeded 90% of your data usage' });
صفحة حساب المستخدم (مثال)
if messages . warning
.alert.alert-warning.fade.in
for warning in messages . warning
div = warning . msg partials/flash.pug هو قالب جزئي يحتوي على كيفية تنسيق رسائل الفلاش. في السابق ، كانت رسائل الفلاش منتشرة في كل طريقة عرض تستخدم رسائل الفلاش (الاتصال ، تسجيل الدخول ، التسجيل ، الملف الشخصي) ، ولكن الآن ، لحسن الحظ يستخدم نهجًا جافًا .
يتم تضمين القالب الجزئي رسائل الفلاش في layout.pug .
body
include partials/header
.container
include partials/flash
block content
include partials/footerإذا كان لديك أي أسئلة أخرى حول رسائل الفلاش ، فلا تتردد في فتح مشكلة ، وسأقوم بتحديث هذا الدليل المصغر وفقًا لذلك ، أو إرسال طلب سحب إذا كنت ترغب في تضمين شيء فاتني.
طريقة أكثر صحة للقول إن هذا سيكون "كيف يمكنني إنشاء طريق جديد؟" 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 . nameهذا كل شيء! 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(); مع الرمز التالي:
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' ) , ( ) => {ل
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.