Nodejs 및 프론트 엔드 mysql 추가, 삭제, 수정 및 확인, 파일 업로드, 파일 다운로드, 비디오 온라인 재생 코드

다음은 MySQL 데이터베이스 추가, 삭제, 수정 및 쿼리, 프런트 엔드 파일 업로드 및 다운로드, 프런트 엔드 온라인 비디오 재생을 구현하기 위한 Node.js의 전체 샘플 코드입니다.

백엔드 코드(app.js):

const express = require('express');
const mysql = require('mysql');
const multer = require('multer');

const app = express();
const upload = multer({ dest: 'uploads/' });

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'database_name'
});

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL database!');
});

app.use(express.static('public'));

app.get('/api/users', (req, res) => {
  const sql = 'SELECT * FROM users';
  connection.query(sql, (err, results) => {
    if (err) throw err;
    res.json(results);
  });
});

app.post('/api/users', (req, res) => {
  const { name, email } = req.body;
  const sql = `INSERT INTO users (name, email) VALUES ('${name}', '${email}')`;
  connection.query(sql, (err, result) => {
    if (err) throw err;
    res.json({ message: 'User added successfully!', id: result.insertId });
  });
});

app.put('/api/users/:id', (req, res) => {
  const { name, email } = req.body;
  const id = req.params.id;
  const sql = `UPDATE users SET name='${name}', email='${email}' WHERE id=${id}`;
  connection.query(sql, (err, result) => {
    if (err) throw err;
    res.json({ message: 'User updated successfully!', id: id });
  });
});

app.delete('/api/users/:id', (req, res) => {
  const id = req.params.id;
  const sql = `DELETE FROM users WHERE id=${id}`;
  connection.query(sql, (err, result) => {
    if (err) throw err;
    res.json({ message: 'User deleted successfully!', id: id });
  });
});

app.post('/api/upload', upload.single('file'), (req, res) => {
  console.log(req.file);
  res.json({ message: 'File uploaded successfully!' });
});

app.get('/api/download/:filename', (req, res) => {
  const filename = req.params.filename;
  res.download(`public/${filename}`);
});

app.get('/api/video/:filename', (req, res) => {
  const filename = req.params.filename;
  res.sendFile(`public/${filename}`);
});

app.listen(3000, () => {
  console.log('Server started on port 3000!');
});

 프런트엔드 코드:

<!DOCTYPE html>
<html>
<head>
  <title>Node.js MySQL File Upload and Download Example</title>
</head>
<body>
  <h1>Node.js MySQL File Upload and Download Example</h1>

  <h2>Users</h2>
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody id="users-table-body">
    </tbody>
  </table>

  <h2>Add User</h2>
  <form>
    <label for="name-input">Name:</label>
    <input type="text" id="name-input" name="name"><br><br>
    <label for="email-input">Email:</label>
    <input type="email" id="email-input" name="email"><br><br>
    <button type="submit" onclick="addUser()">Add User</button>
  </form>

  <h2>Upload File</h2>
  <form>
    <input type="file" id="file-input">
    <button type="submit" onclick="uploadFile()">Upload</button>
  </form>

  <h2>Download File</h2>
  <a href="/api/download/file.txt" download>Download</a>

  <h2>Play Video</h2>
  <video src="/api/video/video.mp4" controls></video>

  <script>
    function getUsers() {
      fetch('/api/users')
        .then(response => response.json())
        .then(data => {
          const usersTableBody = document.getElementById('users-table-body');
          usersTableBody.innerHTML = '';
          data.forEach(user => {
            const tr = document.createElement('tr');
            const idTd = document.createElement('td');
            idTd.textContent = user.id;
            const nameTd = document.createElement('td');
            nameTd.textContent = user.name;
            const emailTd = document.createElement('td');
            emailTd.textContent = user.email;
            const actionsTd = document.createElement('td');
            const editButton = document.createElement('button');
            editButton.textContent = 'Edit';
            editButton.onclick = () => editUser(user.id, user.name, user.email);
            const deleteButton = document.createElement('button');
            deleteButton.textContent = 'Delete';
            deleteButton.onclick = () => deleteUser(user.id);
            actionsTd.appendChild(editButton);
            actionsTd.appendChild(deleteButton);
            tr.appendChild(idTd);
            tr.appendChild(nameTd);
            tr.appendChild(emailTd);
            tr.appendChild(actionsTd);
            usersTableBody.appendChild(tr);
          });
        })
        .catch(error => console.error(error));
    }

    function addUser() {
      const nameInput = document.getElementById('name-input');
      const emailInput = document.getElementById('email-input');
      const name = nameInput.value;
      const email = emailInput.value;
      fetch('/api/users', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ name, email })
      })
        .then(response => response.json())
        .then(data => {
          console.log(data);
          getUsers();
        })
        .catch(error => console.error(error));
    }

    function editUser(id, name, email) {
      const newName = prompt('Enter new name:', name);
      const newEmail = prompt('Enter new email:', email);
      fetch(`/api/users/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ name: newName, email: newEmail })
      })
        .then(response => response.json())
        .then(data => {
          console.log(data);
          getUsers();
        })
        .catch(error => console.error(error));
    }

    function deleteUser(id) {
      fetch(`/api/users/${id}`, {
        method: 'DELETE'
      })
        .then(response => response.json())
        .then(data => {
          console.log(data);
          getUsers();
        })
        .catch(error => console.error(error));
    }

    function uploadFile() {
      const fileInput = document.getElementById('file-input');
      const file = fileInput.files[0];
      const formData = new FormData();
      formData.append('file', file);

      fetch('/api/upload', {
        method: 'POST',
        body: formData
      })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error(error));
    }

    getUsers();
  </script>
</body>
</html>

참고: 사용하기 전에  database_name MySQL 데이터베이스 이름,  password MySQL 데이터베이스 암호,  file.txt 다운로드하려는 파일 이름 및  video.mp4 재생하려는 비디오 파일 이름으로 바꾸십시오. public 또한 샘플 코드가 작동하려면 프로젝트의 루트에 이라는 폴더를  만들고 video.mp4 그 안에 이라는 비디오 파일을 추가 해야 합니다  .

추천

출처blog.csdn.net/m0_59799878/article/details/129545498