search
HomeWeb Front-endFront-end Q&Anodejs implements post-it message board

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:



  <meta charset="UTF-8">
  <title>Node.js Notepad</title>
  <link rel="stylesheet" href="/css/styles.css">


  <div class="container">
    <h1 id="Node-js-Notepad">Node.js Notepad</h1>
    <form>
      <textarea id="note" placeholder="Enter your note"></textarea>
      <button type="submit">Save</button>
    </form>
    <div id="notes">
      
        <div class="note">
          <span class="delete" data-id="<%= note.id %>">x</span>
          <p></p>
        </div>
      
    </div>
  </div>
  <script src="/js/scripts.js"></script>

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></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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.