标签:前后端整合、Vue.js、Express.js、MongoDB、API 调用、CRUD 操作、入门教程、项目实践

前言

欢迎来到“前后端与数据库交互详解”系列的第7篇文章!在前六篇文章中,我们分别学习了 Vue.js 前端基础(组件、HTTP 请求)、Node.js/Express 后端(RESTful API)、和 MongoDB 数据库连接。现在,是时候将它们整合起来:让前端调用后端 API 操作数据库。

本篇文章的焦点是 前后端整合,特别是用 Vue.js 通过 Axios 调用 Express API 来操作 MongoDB 数据。我们将解释整合是什么、如何实现,并在结尾构建一个完整的“用户管理系统”应用:一个 Vue 前端界面,支持用户列表显示、添加、编辑和删除(CRUD),数据存储在 MongoDB 中。这将帮助您理解全栈开发流程,形成一个可运行的独立应用。未来,我们将添加认证和部署。

前提:您已安装 Vue CLI(从第一篇)、Express 和 Mongoose(从第五、第六篇)。我们基于第六篇的 MongoDB 用户 API 扩展。如果有 CORS 问题,安装 cors 模块(npm install cors)并在 Express 中启用 app.use(require('cors')());

一、前后端整合是什么?

前后端整合是指前端(Vue.js)通过 HTTP 请求调用后端(Express API),后端处理逻辑并与数据库(MongoDB)交互,返回数据给前端显示或更新。

  • 为什么整合?

    • 数据流动:前端不直接访问数据库(安全),而是通过 API 中转。
    • 分离关注:前端专注 UI,后端专注业务和数据。
    • RESTful 交互:用 GET/POST/PUT/DELETE 操作资源。
    • 对比独立开发:前文的前端(如第三篇天气查询)是孤立的;整合后,它成为完整应用。
    • 工具:Axios(第三篇)发送请求,Express 处理路由,Mongoose 操作 MongoDB。
  • 核心概念

    • API 调用:Vue 中用 Axios.get(‘/api/users’) 获取数据。
    • 状态管理:Vue data 或 computed 处理响应。
    • CRUD:Create (POST)、Read (GET)、Update (PUT)、Delete (DELETE)。
    • CORS:跨域资源共享,确保前端(e.g., localhost:8080)能访问后端(localhost:3000)。

在我们的系列中,这是关键一步:从分离到统一的 full-stack 应用。

二、前后端整合的基本使用

  1. 后端准备:扩展 Express API 支持完整 CRUD。
  2. 前端调用:在 Vue 组件中使用 Axios 发送请求,处理响应。
  3. 数据绑定:用 v-model 和 v-for 显示/更新 UI。
  4. 错误处理:捕获 404 等状态。

示例:Vue 组件中 axios.get('http://localhost:3000/api/users').then(res => this.users = res.data)

接下来,通过项目实践这些。

三、实现完整项目:用户管理系统

项目目标:构建一个 full-stack 应用。前端:Vue 界面显示用户列表、表单添加/编辑用户、删除按钮。后端:扩展第六篇的 Express API 支持 PUT/DELETE,连接 MongoDB。数据实时同步,支持 CRUD。这是一个独立的完整应用,可以运行前后端,交互用户数据。

步骤 1: 后端部分(扩展 Express API)

基于第六篇,新建/更新 server.js(添加 PUT/DELETE 和 CORS):

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const PORT = 3000;

app.use(cors()); // 启用 CORS
app.use(express.json());

// 连接 MongoDB(替换为您的字符串)
mongoose.connect('mongodb://localhost:27017/userdb', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error('MongoDB connection error:', err));

const userSchema = new mongoose.Schema({ name: String, email: String });
const User = mongoose.model('User', userSchema);

// GET all
app.get('/api/users', async (req, res) => {
  const users = await User.find();
  res.json(users);
});

// GET one
app.get('/api/users/:id', async (req, res) => {
  const user = await User.findById(req.params.id);
  if (user) res.json(user); else res.status(404).json({ error: 'Not found' });
});

// POST
app.post('/api/users', async (req, res) => {
  const newUser = new User(req.body);
  await newUser.save();
  res.status(201).json(newUser);
});

// PUT (update)
app.put('/api/users/:id', async (req, res) => {
  const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
  if (user) res.json(user); else res.status(404).json({ error: 'Not found' });
});

// DELETE
app.delete('/api/users/:id', async (req, res) => {
  await User.findByIdAndDelete(req.params.id);
  res.status(204).send();
});

app.listen(PORT, () => console.log(`Server on http://localhost:${PORT}`));
  • 新增:PUT 更新用户,DELETE 删除;CORS 允许前端访问。

运行:node server.js

步骤 2: 前端部分(Vue 应用)

基于第一/二/三篇,新建 Vue 项目(vue create user-manager-vue),或扩展现有。在 src/components/UserManager.vue 中编写:

<template>
  <div>
    <h1>用户管理系统</h1>
    <!-- 用户列表 -->
    <ul>
      <li v-for="user in users" :key="user._id">
        {{ user.name }} ({{ user.email }})
        <button @click="editUser(user)">编辑</button>
        <button @click="deleteUser(user._id)">删除</button>
      </li>
    </ul>
    <!-- 表单 -->
    <form @submit.prevent="saveUser">
      <input v-model="currentUser.name" placeholder="Name" required />
      <input v-model="currentUser.email" placeholder="Email" required />
      <button type="submit">{{ editing ? '更新' : '添加' }}</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      users: [],
      currentUser: { name: '', email: '' },
      editing: false,
      editingId: null
    };
  },
  mounted() {
    this.fetchUsers();
  },
  methods: {
    async fetchUsers() {
      const res = await axios.get('http://localhost:3000/api/users');
      this.users = res.data;
    },
    async saveUser() {
      if (this.editing) {
        await axios.put(`http://localhost:3000/api/users/${this.editingId}`, this.currentUser);
      } else {
        await axios.post('http://localhost:3000/api/users', this.currentUser);
      }
      this.resetForm();
      this.fetchUsers();
    },
    editUser(user) {
      this.currentUser = { ...user };
      this.editing = true;
      this.editingId = user._id;
    },
    async deleteUser(id) {
      await axios.delete(`http://localhost:3000/api/users/${id}`);
      this.fetchUsers();
    },
    resetForm() {
      this.currentUser = { name: '', email: '' };
      this.editing = false;
      this.editingId = null;
    }
  }
};
</script>
  • 解释
    • fetchUsers:GET 获取列表,用 v-for 显示。
    • saveUser:POST 添加或 PUT 更新。
    • deleteUser:DELETE 删除后刷新。
    • 表单:v-model 绑定,@submit 处理。

App.vue 中导入 <UserManager />

步骤 3: 运行和测试

  • 后端:node server.js(localhost:3000)。
  • 前端:npm run serve(localhost:8080)。
  • 测试:添加用户,看到列表更新;编辑/删除,数据实时变化(MongoDB 持久化)。
  • 这是一个完整的 full-stack 应用!前端调用 API 操作数据库。

步骤 4: 扩展(可选)

  • 添加验证:Vue 中检查输入,后端用 Mongoose schema。
  • 状态管理:用 Vuex(未来文章)。
  • 路由:用 Vue Router 多个页面。

四、常见问题与调试

  • CORS 错误?确保后端启用 cors。
  • API URL?本地开发用 http://localhost:3000;生产用相对路径或环境变量。
  • ID 处理?MongoDB 用 _id,确保类型匹配。
  • 异步加载?用 loading 状态显示 spinner。

总结

通过本篇,您学会了前后端整合,用 Vue.js 调用 Express API 操作 MongoDB。用户管理系统证明了如何构建 CRUD 应用,形成独立的全栈项目。

下一篇文章:用户认证基础:JWT 在 Express 中的实现,实现安全登录。我们将添加认证,保护 API。如果有疑问,欢迎评论!

(系列导航:这是第7/20篇。关注我,跟着学完整系列!)

更多推荐