напиши expressjs код
- User
напиши expressjs код
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
напиши expressjs код
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Конечно! Вот простой пример приложения на Express.js, которое создает RESTful API для управления задачами (to-do list).
Убедитесь, что у вас установлен Node.js. Если нет, скачайте и установите его с официального сайта Node.js.
Создайте новую папку для вашего проекта и перейдите в неё:
mkdir my-todo-app
cd my-todo-app
Инициализируйте новый проект Node.js:
npm init -y
Установите Express.js:
npm install express
Создайте файл index.js и добавьте в него следующий код:
const express = require('express');
const app = express();
const port = 3000;
// Middleware для парсинга JSON
app.use(express.json());
// Массив для хранения задач
let todos = [];
// Маршрут для получения всех задач
app.get('/todos', (req, res) => {
res.json(todos);
});
// Маршрут для создания новой задачи
app.post('/todos', (req, res) => {
const { task } = req.body;
if (!task) {
return res.status(400).json({ error: 'Task is required' });
}
const newTodo = { id: todos.length + 1, task, completed: false };
todos.push(newTodo);
res.status(201).json(newTodo);
});
// Маршрут для обновления задачи
app.put('/todos/:id', (req, res) => {
const { id } = req.params;
const { task, completed } = req.body;
const todo = todos.find(t => t.id === parseInt(id));
if (!todo) {
return res.status(404).json({ error: 'Todo not found' });
}
if (task) todo.task = task;
if (completed !== undefined) todo.completed = completed;
res.json(todo);
});
// Маршрут для удаления задачи
app.delete('/todos/:id', (req, res) => {
const { id } = req.params;
todos = todos.filter(t => t.id !== parseInt(id));
res.status(204).send();
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Запустите сервер:
node index.js
Теперь ваше приложение работает, и вы можете взаимодействовать с ним с помощью инструментов, таких как Postman или curl.
Получить все задачи:
GET http://localhost:3000/todos
Создать новую задачу:
POST http://localhost:3000/todos
Content-Type: application/json
{
"task": "Прочитать книгу"
}
Обновить задачу:
PUT http://localhost:3000/todos/1
Content-Type: application/json
{
"task": "Прочитать книгу о JavaScript",
"completed": true
}
Удалить задачу:
DELETE http://localhost:3000/todos/1
Этот код создает простой API для управления задачами. Вы можете расширить его, добавив базы данных и дополнительные функции по мере необходимости.