零基础后端学习
2026/7/1 4:24:10 网站建设 项目流程

​​以下是为零后端基础学习者量身定制的后端实现详细指南。我将用最直白的语言、分步骤拆解每个操作,包含完整可运行的代码示例关键原理图解,确保你跟着做就能跑通项目。


一、从零开始:后端环境搭建(5分钟搞定)

步骤1:安装基础工具
  1. Node.js(后端运行环境)

    • 下载地址:https://nodejs.org/ (选LTS版本,带"Recommended for Most Users"标识)
    • 安装后打开命令行(Windows用cmd,Mac用Terminal),输入:
      node -v # 应显示 v20.x.x npm -v # 应显示 10.x.x
  2. PostgreSQL(数据库)

    • 下载地址:PostgreSQL: Downloads
    • 安装时记住设置的密码(后面会用到)
    • 安装后打开pgAdmin 4(自动安装的图形化工具):
      • 右键ServersCreateServer
      • 填写连接名(如mydb),在Connection标签页填:
        • Host:localhost
        • Port:5432
        • Username:postgres(默认)
        • Password: 你安装时设的密码
步骤2:创建第一个后端项目
# 1. 创建项目文件夹 mkdir my-task-backend && cd my-task-backend # 2. 初始化Node.js项目(全部按回车用默认值) npm init -y # 3. 安装核心依赖 npm install express prisma @prisma/client bcryptjs jsonwebtoken cors dotenv npm install -D prisma nodemon # 4. 初始化Prisma(数据库工具) npx prisma init

✅ 此时项目结构:

文本
my-task-backend/ ├── node_modules/ # 依赖包(自动生成) ├── .env # 环境变量文件 ├── prisma/ # 数据库配置 │ └── schema.prisma ├── package.json # 项目配置 └── package-lock.json

二、数据库设计:用最简单的方式建表(关键!)

步骤1:修改数据库连接配置

打开.env文件,替换你的密码

DATABASE_URL="postgresql://postgres:你的密码@localhost:5432/mydb?schema=public"
步骤2:定义用户表(只做最简版)

打开prisma/schema.prisma删除所有内容,粘贴以下代码:

// 只保留用户注册登录必需的字段 model User { id Int @id @default(autoincrement()) email String @unique // 唯一标识 password String // 加密后的密码 }
步骤3:创建数据库表
npx prisma migrate dev --name init

✅ 执行后会:

  1. 自动在PostgreSQL创建mydb数据库
  2. 生成User表(包含 id/email/password 字段)
  3. 打开 pgAdmin → 刷新数据库 → 展开SchemasTables就能看到User

三、实现用户注册功能(核心代码详解)

步骤1:创建基础服务器文件

新建index.js(项目根目录):

// 1. 引入依赖 const express = require('express'); const cors = require('cors'); const { PrismaClient } = require('@prisma/client'); const bcrypt = require('bcryptjs'); // 2. 初始化工具 const app = express(); const prisma = new PrismaClient(); const saltRounds = 10; // 密码加密强度 // 3. 允许前端访问(解决跨域问题) app.use(cors()); app.use(express.json()); // 解析JSON请求体 // 4. 注册接口 app.post('/api/register', async (req, res) => { try { // 从请求中获取邮箱和密码 const { email, password } = req.body; // 检查邮箱是否已存在 const existingUser = await prisma.user.findUnique({ where: { email } }); if (existingUser) { return res.status(400).json({ error: "邮箱已注册" }); } // 用bcrypt加密密码(安全关键!) const hashedPassword = await bcrypt.hash(password, saltRounds); // 保存到数据库 const newUser = await prisma.user.create({ data: { email, password: hashedPassword } }); // 返回成功响应(不返回密码!) res.status(201).json({ id: newUser.id, email: newUser.email }); } catch (error) { res.status(500).json({ error: "服务器错误" }); } }); // 5. 启动服务器 const PORT = 3000; app.listen(PORT, () => { console.log(`后端运行中: http://localhost:${PORT}`); });
步骤2:测试注册功能
  1. 启动后端(命令行执行):

    node index.js

    ✅ 看到后端运行中: http://localhost:3000表示成功

  2. 用Postman测试(下载地址:Download Postman | Get Started for Free

    ):

    • 方法:POST
    • URL:http://localhost:3000/api/register
    • Body → raw → JSON:json
      { "email": "test@example.com", "password": "123456" }
    • 点击Send→ 返回成功数据即表示注册成功
  3. 验证数据是否存入数据库

    • 打开 pgAdmin → 右键User表 →View/Edit DataAll Rows
    • 你会看到password字段是一串加密字符串(不是明文!)

四、实现用户登录功能(含JWT认证)

步骤1:生成JWT密钥

.env文件末尾添加(不要用示例密钥!):

JWT_SECRET="your_strong_secret_here_123" # 换成你自己的随机字符串
步骤2:在index.js中添加登录接口
// 在 const saltRounds = 10; 下方添加 const jwt = require('jsonwebtoken'); require('dotenv').config(); // 读取 .env 文件 // 新增登录接口 app.post('/api/login', async (req, res) => { try { const { email, password } = req.body; // 1. 检查用户是否存在 const user = await prisma.user.findUnique({ where: { email } }); if (!user) { return res.status(401).json({ error: "邮箱或密码错误" }); } // 2. 验证密码(用bcrypt.compare) const isPasswordValid = await bcrypt.compare(password, user.password); if (!isPasswordValid) { return res.status(401).json({ error: "邮箱或密码错误" }); } // 3. 生成JWT令牌(有效期2小时) const token = jwt.sign( { userId: user.id, email: user.email }, // 携带用户信息 process.env.JWT_SECRET, { expiresIn: '2h' } ); // 4. 返回令牌(前端会保存到localStorage) res.json({ token }); } catch (error) { res.status(500).json({ error: "服务器错误" }); } });
步骤3:测试登录
  1. 用Postman发送请求:
    • URL:http://localhost:3000/api/login
    • Body:
      { "email": "test@example.com", "password": "123456" }
  2. 成功响应示例
    { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImVtYWlsIjoidGVzdEBleGFtcGxlLmNvbSIsImlhdCI6MTcxOTY3MjAwMCwiZXhwIjoxNzE5Njc5MjAwfQ.xxxxx" }

    🔑 这个token就是后续请求的"通行证",复制它备用


五、保护需要登录的接口(权限控制)

步骤1:创建认证中间件

index.js顶部添加:

// 验证JWT的中间件 function authenticateToken(req, res, next) { // 1. 从请求头获取token const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; // 格式: "Bearer xyz" if (!token) return res.status(401).json({ error: "未提供令牌" }); // 2. 验证token jwt.verify(token, process.env.JWT_SECRET, (err, user) => { if (err) return res.status(403).json({ error: "令牌无效" }); // 3. 将用户信息存入req对象,后续接口可用 req.user = user; next(); // 继续执行后续逻辑 }); }
步骤2:创建需要登录的接口

index.js末尾添加:

// 受保护的接口示例 app.get('/api/profile', authenticateToken, async (req, res) => { // req.user 包含JWT中的信息(userId/email) const user = await prisma.user.findUnique({ where: { id: req.user.userId }, select: { id: true, email: true } // 只返回必要字段 }); res.json(user); });
步骤3:测试受保护接口
  1. 在Postman中:
    • URL:http://localhost:3000/api/profile
    • Headers 添加:
      KeyValue
      AuthorizationBearer 你之前复制的token
  2. 成功响应
    { "id": 1, "email": "test@example.com" }
  3. 如果删除token或改错,会返回401 Unauthorized

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询