完整的后端课程 | NodeJS、ExpressJS、JWT、Prisma、PostgreSQL

完整的后端课程 | NodeJS、ExpressJS、JWT、Prisma、PostgreSQL

视频地址:Complete Backend Course | NodeJS, ExpressJS, JWT, Prisma, PostgreSQL

Github源代码地址:https://github.com/machadop1407/NodeJS-ExpressJS-BackendCourse

Complete Backend Course | NodeJS, ExpressJS, JWT, Prisma, PostgreSQL

Build a Complete Backend API with Authentication, Movie Management & Watchlist Features

Follow the full video tutorial on YouTube

📋 Table of Contents

  1. Introduction

  2. [Tech Stack](#Tech Stack)

  3. Features

  4. [Quick Start](#Quick Start)

  5. [API Endpoints](#API Endpoints)

  6. [Database Schema](#Database Schema)

  7. Deployment

  8. [Course & Channel](#Course & Channel)


🚀 Introduction

In this comprehensive backend course, you'll learn how to build a complete RESTful API from scratch using Node.js , Express.js, and modern backend development practices. This video walks you through building:

  1. User Authentication System - Secure registration, login, and JWT-based authentication

  2. Movie Management API - Full CRUD operations for movie data

  3. Watchlist Feature - Personal watchlist with status tracking and ratings

Perfect for developers looking to master backend development, learn API design, implement authentication, work with databases using Prisma ORM, and build production-ready backend applications.

🎥 Watch the full tutorial : YouTube


⚙️ Tech Stack

  • Node.js -- JavaScript runtime for server-side development

  • Express.js -- Fast, minimalist web framework for Node.js

  • JWT (JSON Web Tokens) -- Secure authentication and authorization

  • Prisma -- Next-generation ORM for database management

  • PostgreSQL -- Powerful, open-source relational database

  • Zod -- TypeScript-first schema validation library

  • bcryptjs -- Password hashing for secure user authentication

  • dotenv -- Environment variable management


⚡️ Features

🔐 Authentication System

  • 📝 User Registration - Secure user signup with email validation

  • 🔑 User Login - JWT-based authentication with token generation

  • 🚪 User Logout - Token invalidation and session management

  • 🔒 Password Hashing - Secure password storage using bcryptjs

  • 🛡️ Protected Routes - Middleware-based route protection

🎬 Movie Management

  • 📋 CRUD Operations - Create, read, update, and delete movies

  • 🎯 Movie Details - Store title, overview, release year, genres, runtime, and poster URLs

  • 👤 User Association - Track which user created each movie

  • 🔍 Query Support - Filter and search movie data

📺 Watchlist System

  • Add to Watchlist - Save movies to personal watchlist

  • 📊 Status Tracking - Track watch status (Planned, Watching, Completed, Dropped)

  • Rating System - Rate movies with optional notes

  • 🗑️ Remove Items - Delete movies from watchlist

  • ✏️ Update Items - Modify watchlist item status and ratings

🛠️ Additional Features

  • Request Validation - Zod schema validation for all endpoints

  • 🚨 Error Handling - Centralized error handling middleware

  • 🔐 JWT Middleware - Automatic token verification for protected routes

  • 🗄️ Database Migrations - Prisma migrations for schema management

  • 🌱 Database Seeding - Seed script for initial data


👌 Quick Start

Prerequisites

⚠️ Upgrading This Project to Prisma ORM v7

Prisma ORM v7 introduces breaking changes that affect how this backend project works.

If you want to use Prisma v7 instead of v6 (used in the original tutorial), you must apply all changes below.


🔧 1. Install Prisma v7 Packages

bash 复制代码
npm install @prisma/client@7
npm install -D prisma@7
npm install @prisma/adapter-pg dotenv

🔧 2. Enable ESM in package.json (Required)

Prisma v7 is ESM-only.

json 复制代码
{
  "type": "module"
}

🔧 3. Update Your Prisma Schema

Replace the old generator:

prisma 复制代码
generator client {
  provider = "prisma-client-js"
  engineType = "binary"
}

With the new v7 version:

prisma 复制代码
generator client {
  provider = "prisma-client"
}

🔧 4. Create prisma.config.ts (Required in v7)

Create this file at the project root:

ts 复制代码
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'

export default defineConfig({
  schema: 'prisma/schema.prisma',
  migrations: {
    path: 'prisma/migrations',
    seed: 'tsx prisma/seed.ts',
  },
  datasource: {
    url: env('DATABASE_URL'),
  },
})

Prisma v7 no longer reads connection URLs from the schema.


🔧 5. Update Prisma Client Instantiation

Old (v4--v6):

js 复制代码
import { PrismaClient } from '@prisma/client';
export const prisma = new PrismaClient();

New (Prisma v7):

js 复制代码
import { PrismaClient } from './generated/prisma/client.js';
import { PrismaPg } from '@prisma/adapter-pg';

const adapter = new PrismaPg({
  connectionString: process.env.DATABASE_URL
});

export const prisma = new PrismaClient({ adapter });

This is required across your project wherever Prisma Client is created.


🔧 6. Load .env Manually

Prisma v7 does not automatically load .env.

Install dotenv:

bash 复制代码
npm install dotenv

Add to your entry file (e.g., server.js):

js 复制代码
import "dotenv/config";

🔧 7. Update Node.js Version

Requirement Recommended
Node 20.19.0+ Node 22.x

Prisma v7 will not run on older Node versions.


🔧 8. Removed APIs You Might Be Using

prisma.$use() middleware

→ Replace with client extensions:

js 复制代码
const prisma = new PrismaClient().$extends({
  query: {
    user: {
      async findMany({ args, query }) {
        return query(args);
      }
    }
  }
});

❌ Metrics API removed

If you used $metrics, it no longer exists.


✔️ Summary of Required Changes

Change Required
Update dependencies
ESM mode
New Prisma generator
Add driver adapter
Create prisma.config.ts
Load .env manually
Update client instantiation
Replace middleware (if used) As needed
Update Node version Yes

Installation

  1. Clone the repository
bash 复制代码
git clone https://github.com/yourusername/backend-course.git
cd backend-course
  1. Install dependencies
bash 复制代码
npm install
  1. Set up environment variables

Create a .env file in the root directory:

env 复制代码
DATABASE_URL="postgresql://username:password@localhost:5432/database_name"
JWT_SECRET="your-super-secret-jwt-key"
PORT=5001
  1. Set up the database
bash 复制代码
# Run Prisma migrations
npx prisma migrate dev

# (Optional) Seed the database with sample data
npm run seed:movies
  1. Start the development server
bash 复制代码
npm run dev

The API will be available at: http://localhost:5001


🔌 API Endpoints

Authentication Routes

  • POST /auth/register - Register a new user
  • POST /auth/login - Login and receive JWT token
  • POST /auth/logout - Logout (invalidate token)

Movie Routes

  • GET /movies - Get all movies
  • POST /movies - Create a new movie
  • PUT /movies/:id - Update a movie
  • DELETE /movies/:id - Delete a movie

Watchlist Routes (Protected)

  • POST /watchlist - Add movie to watchlist
  • PUT /watchlist/:id - Update watchlist item
  • DELETE /watchlist/:id - Remove movie from watchlist

🗄️ Database Schema

User Model

  • id - Unique identifier (UUID)
  • name - User's full name
  • email - Unique email address
  • password - Hashed password
  • createdAt - Account creation timestamp

Movie Model

  • id - Unique identifier (UUID)
  • title - Movie title
  • overview - Movie description
  • releaseYear - Year of release
  • genres - Array of genre strings
  • runtime - Movie duration in minutes
  • posterUrl - URL to movie poster image
  • createdBy - User ID of creator
  • createdAt - Creation timestamp

WatchlistItem Model

  • id - Unique identifier (UUID)
  • userId - Reference to User
  • movieId - Reference to Movie
  • status - Watch status (PLANNED, WATCHING, COMPLETED, DROPPED)
  • rating - Optional rating (1-10)
  • notes - Optional personal notes
  • createdAt - Creation timestamp
  • updatedAt - Last update timestamp

☁️ Deployment

Deploy on Railway

  1. Push your code to GitHub

  2. Go to railway.app

  3. Create a new project and import your repository

  4. Add PostgreSQL service

  5. Set environment variables:

    • DATABASE_URL (automatically provided by Railway)
    • JWT_SECRET (generate a secure random string)
    • PORT (Railway will set this automatically)
  6. Deploy your application

Your API will be live on a custom Railway subdomain!

Alternative Deployment Options


🎓 Course & Channel

Learn More with Pedro Technologies

Follow along for more backend tutorials, full-stack development, and practical coding projects!



📝 License

This project is open source and available under the MIT License.


注意事项

运行后台程序

  1. 从Github仓库中下载源代码
    git clone https://github.com/machadop1407/NodeJS-ExpressJS-BackendCourse.git下载源代码

    git clone https://github.com/machadop1407/NodeJS-ExpressJS-BackendCourse.git

可以看到对应的package.json文件如下所示:

javascript 复制代码
{
  "name": "backend-course",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon src/server.js",
    "seed:movies": "node prisma/seed.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "module",
  "dependencies": {
    "@prisma/client": "^6.19.0",
    "bcryptjs": "^3.0.3",
    "dotenv": "^17.2.3",
    "express": "^5.1.0",
    "jsonwebtoken": "^9.0.2",
    "zod": "^4.1.12"
  },
  "devDependencies": {
    "nodemon": "^3.1.11",
    "prisma": "^6.19.0"
  }
}
  1. cd NodeJS-ExpressJS-BackendCourse 即进入到代码根目录,执行npm install安装相关依赖比如express、bcryptjs、dotenv、jsonwebtoken、zod、@prisma/client等

  2. 创建环境变量

    在代码根目录首先创建一个.env的文件,内容如下:

env 复制代码
DATABASE_URL="postgresql://username:password@localhost:5432/database_name"
JWT_SECRET="your-super-secret-jwt-key"
PORT=5001

这里的数据库URL地址需要根据自己实际的用户名和密码,还有数据库名称进行对应配置

JWT密钥可以根据需要自行设置,端口号也可以自行更改

  1. 启动数据库
bash 复制代码
# Run Prisma migrations
npx prisma migrate dev

# (Optional) Seed the database with sample data
npm run seed:movies
  1. 启动开发环境
bash 复制代码
npm run dev

Http Server服务器运行地址:http://localhost:5001

相关推荐
__zRainy__2 小时前
Node系列 · Express:cookie 的基本概念
express
草莓熊Lotso2 小时前
【Redis 初阶】Set 类型深度解析:去重集合的运算能力与实战场景
linux·网络·数据库·windows·redis·tcp/ip·缓存
煎饼皮皮侠3 小时前
【设计】设计一个web版的数据库管理平台后端(之五) --借鉴mybatis
数据库·mybatis
东风破_9 小时前
danci 2:创建的单词书到底存在哪里?从 Supabase 一路理解 ORM、Drizzle 和 RLS
数据库·后端·node.js
东风破_10 小时前
danci 项目(三):从 JSON 数据到 AI Coding,真实项目里的数据清洗、Prompt 和工程规范
前端·后端·node.js
东风破_10 小时前
danci 项目(一):从需求到架构,一个单词学习系统为什么会这样设计
前端·后端·node.js
橙子家11 小时前
OSS 文件上传的几个风险点和解决方案
数据库
2601_9620664912 小时前
【Sql Server】Update中的From语句,以及常见更新操作方式
android·java·数据库
愤怒的苹果ext13 小时前
MySQL Shell备份恢复数据库
数据库·mysql·备份恢复·mysqlsh
数字新视界15 小时前
DCIM管理系统的技术架构与部署模式详解
数据库·物联网·数据中心·数据中心基础设施管理·dcim管理系统