كيفية بناء REST API باستخدام Express.js

كيفية بناء REST API باستخدام Express.js

Express هو إطار عمل ويب خفيف لـ Node.js. يشرح هذا الدليل بناء REST API بسيطة. يجب تثبيت Node.js أولًا.

1. إعداد المشروع

mkdir api && cd api
npm init -y
npm install express

2. إنشاء السيرفر

// index.js
const express = require('express');
const app = express();
app.use(express.json());

let items = [{ id: 1, name: 'Cloudesta' }];

app.get('/items', (req, res) => res.json(items));
app.post('/items', (req, res) => {
  const item = { id: Date.now(), name: req.body.name };
  items.push(item);
  res.status(201).json(item);
});

app.listen(3000, () => console.log('API on http://localhost:3000'));

3. التشغيل

node index.js

4. اختبار نقاط النهاية (Endpoints)

curl http://localhost:3000/items
curl -X POST -H "Content-Type: application/json" -d '{"name":"New"}' http://localhost:3000/items

في بيئة الإنتاج، شغّل التطبيق خلف Nginx كوكيل عكسي (Reverse Proxy) واستخدم PM2 لإبقائه يعمل باستمرار.

هل كانت المقالة مفيدة ؟

0 أعضاء وجدوا هذه المقالة مفيدة

Powered by WHMCompleteSolution