完整的后端课程 | 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

相关推荐
ClickHouseDB13 小时前
ClickHouse Cloud 与 Snowflake 实时性价比对比:CostBench 测试中的 412 倍差距来
运维·数据库·系统架构
m0_6399069413 小时前
Redis入门|五种数据结构、使用场景、持久化RDB&AOF
数据结构·数据库·redis
时间售卖铺14 小时前
触发器与函数实战:MySQL高效编程秘诀
运维·数据库·mysql·云原生
qetfw14 小时前
UOS MariaDB 数据库:安装、最小权限与备份验证
linux·数据库·mariadb·uos
数智园区合作社15 小时前
问数平台怎么把同一个指标锁成一个数
大数据·数据库·人工智能·ai
lbb 小魔仙15 小时前
Windows搭建PaddleOCR+飞书Webhook自动打卡通知机器人:识别、推送与远程触发完整教程
数据库·人工智能·prometheus·时序数据库
captain37616 小时前
MyBatis操作数据库(入门2)
java·数据库·spring boot·后端·spring·mybatis
心中有你021417 小时前
Java实现Dijkstra最短路径算法(邻接表 + 优先队列)
java·数据库·算法
龙亘川17 小时前
综合素质评价业务建模:从过程性评价到成长档案全链路闭环
数据库·智慧城市·数据可视化
数据库小组17 小时前
NineData 实战教程:MySQL 5.5 数据迁移同步到 MySQL 8.0(跨版本升级)
数据库·mysql·mysql优化·数据库开发·数据库迁移·版本升级·数据复制