מאגר מידע

How to Build a REST API with Express.js

Express is a minimal web framework for Node.js. This guide builds a simple REST API. Node.js must be installed first.

1. Set up the project

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

2. Create the server

// 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. Run it

node index.js

4. Test the endpoints

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

For production, run behind Nginx as a reverse proxy and keep it alive with PM2.

?האם התשובה שקיבלתם הייתה מועילה

0 משתמשים שמצאו מאמר זה מועיל

Powered by WHMCompleteSolution