المشروع: نربط تطبيق React بالـ API بتاعنا
تطبيق Social اللي بنيته في كورس React بيقرا عنوان الـ server من VITE_API_URL، فبسطر واحد في .env.local بيكلّم الـ API بتاعنا بدل Route Posts. كل الـ routes متفصّلة على نفس العقد. المتصفح بيبعت preflight بـ OPTIONS قبل أي request فيه Authorization، والـ server بيرد بالـ origin المسموح. وتحدي: نسمح لـ npm run preview على port 4173.
نص شرح المعلم والكود الذي كتبه ونتيجة تشغيله، بنفس ترتيب الدرس.
أهلًا بيك. اللحزة اللي كنا مستنيينها من أول الكورس. في كورس React بنيت تطبيق Social، وكان بيكلّم server جاهز اسمه Route Posts. النهارده نخليه يكلّم الـ server بتاعك إنتَ.
ليه ده هيبقى سهل؟ لأننا من أول درس في المشروع، وإحنا ماشيين على نفس شكل Route Posts: نفس الـ routes: users slash signin، و posts، و like، و comments، و follow، و notifications. نفس شكل الرد: success، و data، وجُوّاها posts أو post. نفس الـ header: Authorization، وبعدها Bearer والـ token. يعني تطبيق React مش هيحس بأي فرق.
الخطوات على جهازك: في مشروع Social بتاع React، اعمل ملف dot env dot local. جُوّاه سطر واحد: VITE_API_URL equals http colon slash slash localhost colon three thousand. افتح terminal للـ API، و npm start. و terminal تاني لـ React، و npm run dev برضه. React على port fifty one seventy three، والـ API على three thousand. وفي الـ API: MAX_POST_LENGTH كان أربعين من درس التجربة. الناس هتكتب منشورات بجد، فنرجّعه خمسمية. دلوقتي نشوف إيه اللي بيحصل بالزبط لما React يعمل منشور. قبل الـ POST نفسه، المتصفح بيبعت request صغير بـ OPTIONS، اسمه preflight. بيسأل الـ server: أنا جاي من localhost five one seven three، وعايز أبعت POST، فيه authorization و content-type. ينفع؟ نبعته زي المتصفح بالزبط.
MAX_POST_LENGTH=500
MONGO_URI=mongodb://127.0.0.1:27017/social
JWT_SECRET=dev-only-secret-change-me
JWT_EXPIRES_IN=7d
PUBLIC_URL=http://localhost:3000
CORS_ORIGINS=http://localhost:5173المخرجات
$ node --env-file=.env server.js اتصلنا بـ MongoDB Social API شغال على http://localhost:3000 (development) → OPTIONS /posts ← 204 No Content access-control-allow-headers: authorization,content-type access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE access-control-allow-origin: http://localhost:5173 connection: keep-alive content-length: 0 content-security-policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests cross-origin-opener-policy: same-origin cross-origin-resource-policy: cross-origin keep-alive: timeout=5 origin-agent-cluster: ?1 referrer-policy: no-referrer strict-transport-security: max-age=31536000; includeSubDomains vary: Origin, Access-Control-Request-Headers x-content-type-options: nosniff x-dns-prefetch-control: off x-download-options: noopen x-frame-options: SAMEORIGIN x-permitted-cross-domain-policies: none x-xss-protection: 0
الـ server رد بـ two oh four، من غير body. access-control-allow-origin: بعنوان React بالزبط. access-control-allow-methods: فيها POST. access-control-allow-headers: authorization و content-type. المتصفح شاف الموافقة، فبيبعت الـ request الحقيقي. وده كله cors هو اللي بيعمله، في السطر اللي كتبناه في درس الأمان. والدخول، زي ما صفحة الـ login بتبعته.
المخرجات
$ node --env-file=.env server.js
اتصلنا بـ MongoDB
Social API شغال على http://localhost:3000 (development)
→ POST /users/signin
{"login":"mona","password":"Social@123"}
POST /users/signin 200 - 96 ms
← 200 OK
{
"success": true,
"message": "أهلًا بيك",
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2YWM3MmI1Mzk3ZmJmMDI3NjA5NDFiMjciLCJ2IjowLCJpYXQiOjE3OTE0Mzc2NTQsImV4cCI6MTc5MjA0MjQ1NH0.YoYilqcjGg6serq2Zj_fdm4v2gXqM91TB3DK-hDU6LQ",
"user": {
…الـ token راجع في data dot token، زي Route Posts بالزبط. React بيحفزه، ومن هنا كل الصفحات شغالة: الـ feed، والإعجابات، والتعليقات، والإشعارات، والصور. والصور روابطها من PUBLIC_URL، و helmet سامح بيها من origin تاني. بس فيه مشكلة هتقابلها. في درس النشر في كورس React، جربنا npm run build، وبعدها npm run preview علشان نتأكد من dist. npm run preview بيشتغل على port تاني: four one seven three. نبعت نفس الـ preflight من هناك.
المخرجات
$ node --env-file=.env server.js اتصلنا بـ MongoDB Social API شغال على http://localhost:3000 (development) → OPTIONS /posts ← 204 No Content access-control-allow-headers: authorization,content-type access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE connection: keep-alive content-length: 0 content-security-policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests cross-origin-opener-policy: same-origin cross-origin-resource-policy: cross-origin keep-alive: timeout=5 origin-agent-cluster: ?1 referrer-policy: no-referrer strict-transport-security: max-age=31536000; includeSubDomains vary: Origin, Access-Control-Request-Headers x-content-type-options: nosniff x-dns-prefetch-control: off x-download-options: noopen x-frame-options: SAMEORIGIN x-permitted-cross-domain-policies: none x-xss-protection: 0
مفيش access-control-allow-origin خالص. الـ server مش رافض بـ error، هو بس ما قالش موافق. والمتصفح هو اللي بيوقف الـ request، وفي الـ console بتاع React هتلاقي رسالة CORS حمرا. وده أكتر خطأ هتقابله وإنتَ بتربط front end بـ back end.
دورك. والمطلوب بالزبط: في dot env: CORS_ORIGINS يبقى فيها العنوانين: fifty one seventy three، و comma، و forty one seventy three. من غير مسافات. ونفس الكلام في dot env dot example، علشان أي حد ياخد المشروع يعرف. و config.js بيقسمهم بالـ comma لوحده. عدّل الملفين.
CORS_ORIGINS فيها http://localhost:5173 و http://localhost:4173، في .env و .env.example.
الحل. سطر واحد في كل ملف. نشغل من جديد، ونبعت الـ preflight من four one seven three.
MAX_POST_LENGTH=500
MONGO_URI=mongodb://127.0.0.1:27017/social
JWT_SECRET=
JWT_EXPIRES_IN=7d
PUBLIC_URL=http://localhost:3000
CORS_ORIGINS=http://localhost:5173,http://localhost:4173المخرجات
$ node --env-file=.env server.js اتصلنا بـ MongoDB Social API شغال على http://localhost:3000 (development) → OPTIONS /posts ← 204 No Content access-control-allow-headers: authorization,content-type access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE access-control-allow-origin: http://localhost:4173 connection: keep-alive content-length: 0 content-security-policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests cross-origin-opener-policy: same-origin cross-origin-resource-policy: cross-origin keep-alive: timeout=5 origin-agent-cluster: ?1 referrer-policy: no-referrer strict-transport-security: max-age=31536000; includeSubDomains vary: Origin, Access-Control-Request-Headers x-content-type-options: nosniff x-dns-prefetch-control: off x-download-options: noopen x-frame-options: SAMEORIGIN x-permitted-cross-domain-policies: none x-xss-protection: 0
access-control-allow-origin رجعت، بعنوان four one seven three. الـ cors package بيرجّع العنوان اللي سأل بس، مش القايمة كلها، فمحدش يعرف مين تاني مسموح له. كده تطبيق React كله شغال على الـ API بتاعك، على جهازك. الدرس الجاي: نرفع الاتنين على الإنترنت.
MAX_POST_LENGTH=500
MONGO_URI=mongodb://127.0.0.1:27017/social
JWT_SECRET=dev-only-secret-change-me
JWT_EXPIRES_IN=7d
PUBLIC_URL=http://localhost:3000
CORS_ORIGINS=http://localhost:5173,http://localhost:417303 / دروس الكورس (70)
- 01أهلًا بيك: هنبني إيه في الكورس ده
- 02يعني إيه Node.js؟ وأول برنامج برة المتصفح
- 03process.argv: برنامج بياخد معلومات من الأمر نفسه
- 04Environment variables: إعدادات برة الـ code
- 05تقسيم الـ code على ملفات: require و module.exports
- 06ES modules: import و export، والنظام اللي هنبني بيه المشروع
- 07الـ modules اللي جاية مع Node: path و os و crypto
- 08المشروع: بداية Social API، والبيانات اللي هنشتغل عليها
- 09قراية وكتابة الملفات: fs بالطريقة المتزامنة
- 10ليه Node بيحب الـ async: fs.readFile و callbacks
- 11fs/promises و async/await: نفس الـ async من غير callback hell
- 12ملفات JSON: نخزن objects و arrays ونرجعهم
- 13الـ folders: mkdir و readdir و stat و rm
- 14المشروع: أول database لـ Social على ملفات JSON
- 15blocking: لما الـ thread الواحد يقف، كل حاجة تقف
- 16الـ event loop: مين بيشتغل إمتى
- 17الـ promises من جُوّه: new Promise و resolve و reject
- 18Promise.all وأخواتها: كذا حاجة في نفس الوقت
- 19الأخطاء في الـ async: await المنسية، والخطأ اللي بيوقّع البرنامج
- 20المشروع: Promise.all، و race condition بيضيّع منشور، وطابور للكتابة
- 21الـ events: EventEmitter و on و emit
- 22الـ streams: ملف كبير حتة حتة
- 23pipeline: نوصّل الـ streams ببعض، ونضغط ونفلتر
- 24الـ terminal نفسه stream: process.stdout و readline
- 25المشروع: أداة command line، و events بتسجل النشاط في stream
- 26npm و package.json: بطاقة المشروع والـ scripts
- 27npm install: نستخدم package حد تاني كتبها
- 28المشروع: package.json و scripts و .gitignore و .env
- 29HTTP، وأول server بـ node:http
- 30الـ routing بإيدينا: method و path و query و params
- 31نستقبل body: الـ request نفسه stream
- 32المشروع: Social API على node:http من غير مكتبات
- 33Express: نفس الـ server في نص الـ code
- 34POST و PATCH و DELETE في Express، و express.json
- 35الـ middleware: function في نص الطريق
- 36Router: كل مجموعة routes في ملف
- 37الأخطاء في Express: throw في أي route، ورد واحد من مكان واحد
- 38المشروع: Social API على Express، بترتيب المشاريع الحقيقية
- 39ملفات ثابتة بـ express.static، و CORS علشان React يكلمنا
- 40Zod على الـ server: ما تصدقش أي حاجة جاية من برة
- 41middleware واحد للـ validation في كل الـ routes
- 42المشروع: Zod في Social API، و pagination زي Route Posts
- 43MongoDB: قاعدة بيانات بتخزن documents
- 44Mongoose: Schema و Model بيحددوا شكل البيانات
- 45القراية من MongoDB: find والشروط والترتيب والصفحات
- 46التعديل والمسح: $set و $inc و $addToSet و $pull
- 47العلاقات: ref و populate
- 48المشروع: Social API على MongoDB
- 49كلمات السر: ليه ما بنحفزهاش، و bcrypt
- 50JWT: الـ server يفتكرك إزاي
- 51المشروع: حساب جديد، بـ Zod و bcrypt و MongoDB
- 52المشروع: تسجيل الدخول، ونرجّع token
- 53المشروع: middleware بيحمي الـ routes بالـ token
- 54المشروع: الصلاحيات، منشورك بس اللي تعدّله
- 55المشروع: تغيير كلمة السر، والـ tokens القديمة تبطل
- 56المشروع: نفس شكل Route Posts، والإعجاب
- 57المشروع: التعليقات، و router جُوّه router، وعدد التعليقات
- 58المشروع: حفظ المنشورات، و bookmarked لكل مستخدم
- 59المشروع: المتابعة، وصفحة الـ profile
- 60المشروع: feed الناس اللي بتتابعهم، والاقتراحات
- 61المشروع: الإشعارات من الـ events
- 62رفع الملفات بـ multer
- 63المشروع: منشورات بصور، بنفس الـ FormData اللي React بيبعتها
- 64الأمان: helmet و CORS و rate limiting
- 65الإعدادات: environment variables متفحوصة من أول ثانية
- 66الاختبارات بـ node:test
- 67اختبار الـ API كله: supertest وقاعدة بيانات للاختبار
- 68المشروع: نربط تطبيق React بالـ API بتاعناانت هنا
- 69النشر: MongoDB Atlas و Render
- 70الخلاصة، وإيه الخطوة الجاية