Backend – server.js - 9.3 | Chapter 9: Project – Student Feedback Web App | Full Stack Web Development Basics
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Academics
Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Professional Courses
Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skills—perfect for learners of all ages.

games

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Setting Up the Express Server

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Today, we're going to set up our Express server, which is the backbone of our student feedback application. Does anyone know what Express is?

Student 1
Student 1

Isn't it a framework for Node.js?

Teacher
Teacher

Exactly! Express makes it easier to create server applications. We start by requiring Express and initializing an app. Can someone tell me how we do that?

Student 2
Student 2

We use `const express = require('express');` and `const app = express();` right?

Teacher
Teacher

Good job! Now, let's remember this with the acronym 'E A' — Express and App. Let's move on to serving static files.

Handling JSON Data

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

To manage the data submitted by users, we need to use JSON. How do we handle JSON data in Express?

Student 3
Student 3

We can use `app.use(express.json())` to parse JSON.

Teacher
Teacher

Correct! This allows Express to understand the JSON format we receive from the frontend. Can anyone tell me why this is important?

Student 4
Student 4

So we can easily send and receive data in a format that both the server and client can understand.

Teacher
Teacher

Exactly! To help recall this, remember 'JS E' for 'JSON Support in Express.' Let's proceed with the routes.

Creating Routes

Unlock Audio Lesson

Signup and Enroll to the course for listening the Audio Lesson

0:00
Teacher
Teacher

Now, let’s set up our routes for handling feedback. What are the two routes we need?

Student 1
Student 1

One for getting feedback and another for submitting feedback.

Teacher
Teacher

Right! So, we have a GET route `/feedbacks` to retrieve feedback and a POST route `/submit-feedback` to submit new feedback. Why do you think we need two different types of routes?

Student 2
Student 2

Because one retrieves data, while the other modifies it!

Teacher
Teacher

Great point! Let's remember this with the mnemonic 'GPR for Get, Post, Retrieve.' Now, moving to the feedback storage.

Introduction & Overview

Read a summary of the section's main ideas. Choose from Basic, Medium, or Detailed.

Quick Overview

This section details the implementation of the server using Node.js and Express, focusing on how to manage student feedback.

Standard

In this section, we set up a basic server using Node.js and Express. The server handles GET and POST requests to retrieve and store student feedback in a JSON file, demonstrating how to manage data effectively in a web application.

Detailed

Backend – server.js

In this section, we implement a backend server for the student feedback web application using Node.js and Express.

Key Functionality

  1. Server Setup: We initialize an Express application to handle our routes.
  2. Static Files: We serve static files (HTML, CSS, JavaScript) from the public directory using app.use(express.static('public')).
  3. Middleware: We utilize middleware to handle JSON data sent from the client, allowing us to easily process forms.
  4. Data Retrieval: The GET request at /feedbacks reads existing feedback from feedback.json and responds with it in JSON format.
  5. Data Submission: The POST request at /submit-feedback allows for new feedback entries to be submitted. It checks for existing data, appends new feedback, and writes the updated array back to the JSON file.

Significance

Successfully setting up the backend is crucial for making our web application functional. It connects the frontend interface where students submit their feedback with a persistent storage mechanism, ensuring that feedback is retained even after the server restarts.

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Setting Up the Server

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = 3000;
app.use(express.static('public'));
app.use(express.json());

Detailed Explanation

In this chunk, we see the initial setup for our Express application. We first import the necessary modules: express for creating our server, fs for file system operations, and path for handling file and directory paths. Then, we create an instance of our Express app and define a constant PORT (3000) for the server to listen on. We use app.use(express.static('public')) to serve static files from the 'public' directory, which contains our HTML, CSS, and JavaScript files. Finally, app.use(express.json()) allows the server to parse incoming JSON requests, which is essential for handling feedback submissions.

Examples & Analogies

Think of setting up a server like opening a restaurant. You need to gather all your supplies (like ingredients, utensils) and set up the kitchen (Express, fs, path). Just like you'd have a dedicated area for customers (the 'public' directory), you also need a way to organize your orders (JSON parsing) so everyone gets what they asked for.

Fetching Existing Feedback

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

// Get existing feedback
app.get('/feedbacks', (req, res) => {
const data = fs.readFileSync('feedback.json', 'utf-8') || '[]';
res.json(JSON.parse(data));
});

Detailed Explanation

This chunk defines an endpoint to retrieve existing feedback using HTTP GET requests. The app.get('/feedbacks', ...) function listens for requests to the /feedbacks URL. When a request is received, it reads the content of feedback.json using fs.readFileSync. If the file doesn’t exist or is empty, it defaults to an empty array. The JSON data is then sent back to the client via res.json(). This allows users to see previously submitted feedback when they access the feedback page.

Examples & Analogies

Imagine a library where people come to read books. In this case, the library is your server, and the books are the feedback stored in feedback.json. When someone asks to see a book (feedback), the librarian (our server) checks the shelves (reads from the file) and hands over the books that are available.

Submitting New Feedback

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

// Save new feedback
app.post('/submit-feedback', (req, res) => {
const feedback = req.body;
let data = [];
if (fs.existsSync('feedback.json')) {
data = JSON.parse(fs.readFileSync('feedback.json', 'utf-8'));
}
data.push(feedback);
fs.writeFileSync('feedback.json', JSON.stringify(data, null, 2));
res.json({ message: 'Feedback submitted successfully!' });
});

Detailed Explanation

In this chunk, we define an endpoint for submitting new feedback using HTTP POST requests. The method app.post('/submit-feedback', ...) is designed to handle incoming data from the feedback form. It retrieves the submitted feedback from req.body. If feedback.json already exists, we read its current contents into an array. New feedback is then added to this array, which is saved back into feedback.json using fs.writeFileSync. Finally, we respond to the client with a success message, confirming that their feedback was submitted successfully.

Examples & Analogies

Think of this process like adding a new entry in a guestbook at an event. When new guests arrive (feedback submission), the host checks the existing guestbook (reads feedback.json). If there are previous entries, they get added to the new guest's note (new feedback). Finally, the updated guestbook (saved feedback) is displayed for the next guest to see.

Starting the Server

Unlock Audio Book

Signup and Enroll to the course for listening the Audio Book

app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

Detailed Explanation

The final chunk sets the server to listen on the specified port (3000). The app.listen() function tells the Express server to start accepting connections. When the server is successfully running, it logs a message to the console indicating that it can be accessed at http://localhost:3000. This allows developers to know the server is operational and ready to handle requests.

Examples & Analogies

Starting the server is like opening the doors of your restaurant to customers. When the doors are open (server is listening), potential diners can come in and place their orders (send requests). The sign outside saying 'We’re open!' is like the message in the console, letting everyone know that the service is ready.

Definitions & Key Concepts

Learn essential terms and foundational ideas that form the basis of the topic.

Key Concepts

  • Server Setup: Establishing a backend server using Node.js and Express.

  • Route Handling: Implementing GET and POST routes for data management.

  • JSON Management: Using JSON for data interchange between client and server.

Examples & Real-Life Applications

See how the concepts apply in real-world scenarios to understand their practical implications.

Examples

  • Setting up an Express server with const express = require('express'); const app = express();

  • Using app.get('/feedbacks', ...) to create a route that retrieves existing feedback.

Memory Aids

Use mnemonics, acronyms, or visual cues to help remember key information more easily.

🎵 Rhymes Time

  • In Node we flow, with Express we grow, parsing JSON, making data glow.

📖 Fascinating Stories

  • Imagine a library where feedback is left on slips of paper. Our Express server acts like a librarian who collects those slips, sorts them out, and houses them neatly in a folder.

🧠 Other Memory Gems

  • Remember GPR: Get data with GET, Post new data with POST, Read it with a request.

🎯 Super Acronyms

JS E for JSON Support in Express.

Flash Cards

Review key concepts with flashcards.

Glossary of Terms

Review the Definitions for terms.

  • Term: Express

    Definition:

    A web application framework for Node.js designed for building web applications and APIs.

  • Term: JSON

    Definition:

    JavaScript Object Notation, a lightweight format for data interchange.

  • Term: GET Request

    Definition:

    A request method used to request data from a specified resource.

  • Term: POST Request

    Definition:

    A request method used to submit data to be processed to a specified resource.