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

相关推荐
一颗宁檬不酸9 小时前
文件管理知识点
数据库
9 小时前
达梦数据库-事务
数据库·达梦数据库·dm
网硕互联的小客服10 小时前
MYSQL数据库和MSSQL数据库有什么区别?分别适用于什么脚本程序?
数据库·mysql·sqlserver
weixin_4624462310 小时前
【原创实践】python 获取节假日列表 并保存为excel
数据库·python·excel
RPA 机器人就找八爪鱼11 小时前
RPA 赋能银行数字化转型:四大核心应用场景深度解析
数据库·人工智能·rpa
掂掂三生有幸11 小时前
使用openGauss搭建一个监狱管理系统
数据库
VX:Fegn089511 小时前
计算机毕业设计|基于Java人力资源管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·课程设计
siriuuus11 小时前
Redis 安装、多实例部署、主从复制及 Cluster 实践
数据库·redis·centos
Polaris_GQ11 小时前
Navicat连接Oracle数据库报错:12514问题
数据库