首頁  >  文章  >  web前端  >  nodejs實作便利貼留言板

nodejs實作便利貼留言板

王林
王林原創
2023-05-08 11:53:07561瀏覽

便利貼是人們記錄日常事務、備忘錄和通知的有效方式,而現代技術將其遷移到了數位領域。本文將介紹如何使用 Node.js 建立一個簡單的便利貼留言板,讓使用者可以建立、編輯和刪除便利貼。

首先,需要安裝 Node.js 和 Express 框架。使用以下命令建立專案:

mkdir notepad
cd notepad
npm init
npm install express --save

接下來,建立一個名為index.js 的文件,並新增以下內容:

const express = require('express');
const app = express();
const PORT = 3000;

// 配置视图模板引擎
app.set('view engine', 'ejs');

// 配置静态资源
app.use(express.static('public'));

// 路由
app.get('/', (req, res) => {
  res.render('index');
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

在此程式碼片段中,我們首先導入了Express 框架,並建立了一個名為app 的應用程式。接著,我們設定了應用程式的視圖模板引擎為ejs,並使用express.static 中間件將public 目錄中的靜態資源發布,例如樣式表、JavaScript 檔案和圖像等。然後,我們定義了一個路由值為 /,並在傳回的回應中呼叫 res.render 方法來呈現 index.ejs 視圖範本。最後,我們在連接埠 3000 上啟動伺服器,並在控制台輸出訊息以指示伺服器正在運行。

接下來,建立一個名為index.ejs 的模板,並新增以下內容:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Node.js Notepad</title>
  <link rel="stylesheet" href="/css/styles.css">
</head>
<body>
  <div class="container">
    <h1>Node.js Notepad</h1>
    <form>
      <textarea id="note" placeholder="Enter your note"></textarea>
      <button type="submit">Save</button>
    </form>
    <div id="notes">
      <% for(let note of notes) { %>
        <div class="note">
          <span class="delete" data-id="<%= note.id %>">x</span>
          <p><%= note.content %></p>
        </div>
      <% } %>
    </div>
  </div>
  <script src="/js/scripts.js"></script>
</body>
</html>

此模板定義了一個包含兩個部分的頁面,一個是用於輸入新便利貼的表單,另一個是現有便利貼的清單。在 <script> 標籤中引入了 scripts.js 文件,它將處理表單提交和刪除便利貼的操作。

接下來,建立一個名為notes.js 的文件,並加入以下內容:

class Note {
  static all() {
    return [
      { id: 1, content: 'Buy groceries' },
      { id: 2, content: 'Call John' },
      { id: 3, content: 'Pay rent' }
    ];
  }

  static add(content) {
    const id = Note.all().length + 1;
    const note = { id, content };
    Note.all().push(note);
    return note;
  }

  static remove(id) {
    const notes = Note.all();
    const index = notes.findIndex(note => note.id == id);
    if (index != -1) {
      notes.splice(index, 1);
    }
  }
}

module.exports = Note;

此文件定義了一個Note 類,它有三個靜態方法:alladdremoveNote.all 方法傳回目前的便利貼數組,而 Note.add 方法將新的便利貼加入到數組中。 Note.remove 方法將標識為給定 ID 的便利貼從陣列中刪除。

接下來,建立一個名為controllers.js 的文件,並加入以下內容:

const Note = require('./notes');

exports.home = (req, res) => {
  const notes = Note.all();
  res.render('index', { notes });
};

exports.save = (req, res) => {
  const content = req.body.note;
  const note = Note.add(content);
  res.status(201).json(note);
};

exports.remove = (req, res) => {
  const id = req.params.id;
  Note.remove(id);
  res.status(204).send();
};

此文件定義了三個控制器方法home saveremove,以處理主頁、儲存便利貼和刪除便利貼的請求。 home 方法將所有便利貼作為參數呈現index.ejs 範本;save 方法從請求內文中取得便利貼內容,並使用Note. add 方法建立一個新的便利貼物件;remove 方法從要求的參數中取得要刪除的便利貼ID,並使用Note.remove 方法從便利貼數組中刪除該便利貼。

最後,建立一個名為 scripts.js 的文件,在客戶端處理表單提交和刪除請求。新增以下內容:

function addNoteToList(note) {
  const notes = document.getElementById('notes');
  const noteTemplate = `
    <div class="note">
      <span class="delete" data-id="${note.id}">x</span>
      <p>${note.content}</p>
    </div>
  `;
  notes.innerHTML += noteTemplate;
}

// 处理表单提交
const form = document.querySelector('form');
form.addEventListener('submit', async event => {
  event.preventDefault();
  const content = document.getElementById('note').value;
  const response = await fetch('/', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ note: content })
  });
  const note = await response.json();
  addNoteToList(note);
});

// 处理删除请求
const notes = document.getElementById('notes');
notes.addEventListener('click', async event => {
  if (event.target.classList.contains('delete')) {
    const id = event.target.getAttribute('data-id');
    await fetch(`/${id}`, { method: 'DELETE' });
    event.target.parentElement.remove();
  }
});

此檔案定義了一個 addNoteToList 函數,它將建立一個包含新便利貼內容的 HTML 片段,並將其新增至便利貼清單中。然後,它使用 EventTarget.addEventListener 方法監聽表單提交並發送 POST 請求。它還使用相同的監聽器來偵測刪除按鈕的單擊,發送 DELETE 請求,並從清單中刪除對應的便利貼。

現在我們可以啟動應用程序,運行以下命令:

node index.js

現在可以在瀏覽器中訪問http://localhost:3000,看到一個包含一個表單和現有便利貼的頁面。輸入新的便利貼,點選儲存,便利貼會被加入到清單中。點選刪除按鈕,便利貼就會被刪除。

本文介紹如何使用 Node.js、Express 和 EJS 視圖範本建立一個便利貼留言板,它允許使用者建立、編輯和刪除便利貼。這只是一個簡單的例子,但展示瞭如何使用這些技術來實現實際應用程式。

以上是nodejs實作便利貼留言板的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn