Post-it notes are an effective way for people to record daily affairs, memos and notifications, and modern technology has migrated them to the digital realm. This article will introduce how to use Node.js to create a simple sticky note message board that allows users to create, edit and delete sticky notes.
First, you need to install Node.js and Express framework. Create the project using the following command:
mkdir notepad cd notepad npm init npm install express --save
Next, create a file called index.js
and add the following content:
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}`); });
In this snippet, We first imported the Express framework and created an application named app
. Next, we set the application's view template engine to ejs
and use the express.static
middleware to publish the static resources in the public
directory, such as styles Tables, JavaScript files, images, etc. Then, we define a route value of /
and call the res.render
method in the returned response to render the index.ejs
view template. Finally, we start the server on port 3000 and print a message to the console to indicate that the server is running.
Next, create a template named index.ejs
and add the following content:
<!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>
This template defines a page with two parts, one is a form for entering new sticky notes, and the other is a list of existing sticky notes. The scripts.js
file is introduced in the <script>
tag, which will handle form submission and deletion of sticky notes.
Next, create a file called notes.js
and add the following content:
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;
This file defines a Note
class , which has three static methods: all
, add
, and remove
. The Note.all
method returns the current array of sticky notes, while the Note.add
method adds a new sticky note to the array. Note.remove
Method removes the sticky note identified with the given ID from the array.
Next, create a file called controllers.js
and add the following content:
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(); };
This file defines three controller methodshome
, save
, and remove
, to handle requests for the home page, save sticky notes, and delete sticky notes. The home
method renders all sticky notes as parameters to the index.ejs
template; the save
method gets the sticky note content from the request body and uses Note. The add
method creates a new sticky note object; the remove
method gets the sticky note ID to be deleted from the request parameters, and uses the Note.remove
method to remove it from the sticky note array. Delete the sticky note in .
Finally, create a file named scripts.js
to handle form submission and delete requests on the client side. Add the following content:
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(); } });
This file defines a addNoteToList
function that will create an HTML fragment containing the contents of a new sticky note and add it to the sticky note list. It then uses the EventTarget.addEventListener
method to listen for form submissions and send a POST request. It also uses the same listener to detect delete button clicks, send a DELETE request, and remove the corresponding sticky note from the list.
Now we can launch the application and run the following command:
node index.js
Now we can visit http://localhost:3000 in the browser and see a form containing a form and existing sticky notes page. Enter a new sticky note, click Save, and the sticky note will be added to the list. Click the delete button and the sticky note will be deleted.
This article describes how to use Node.js, Express, and EJS view templates to create a sticky note message board that allows users to create, edit, and delete sticky notes. This is just a simple example, but shows how these techniques can be used to implement a real-world application.
The above is the detailed content of nodejs implements post-it message board. For more information, please follow other related articles on the PHP Chinese website!