课次35:代码调试与BUG修复

一、核心说明

本课次主要针对新闻模块两大功能性BUG进行定位、分析、前后端代码调试与修复,掌握前后端联调排错思路,区分前端逻辑问题与后端数据问题。

二、Bug1:删除非本人新闻,提示删除成功(权限提示异常)

1. Bug现象

用户删除不属于自己发布的新闻时,系统依旧弹出「删除成功」提示,未做权限拦截,不符合业务逻辑。

2. 预期效果

删除非本人新闻 → 拦截删除操作,弹出提示:只能删除自己的新闻;仅本人发布的新闻可正常删除。

3. 问题定位

  • 后端接口逻辑正常,已做权限校验,返回统一封装的Result结果(包含code、message)。

  • 问题根源为前端代码漏洞:前端 deleteNews 请求后未对后端返回的响应结果做判断,直接提示删除成功,忽略后端权限校验失败的返回信息。

4. 修复方案

仅修改前端删除逻辑代码,接收后端Result返回值,根据code状态码判断操作结果:成功则提示成功并刷新页面,失败则读取后端提示文案并弹窗报错。

三、Bug2:用户发布新闻后,个人新闻数量new_count不递增

1. Bug现象

用户成功发布新闻后,数据库user表中对应用户的new_count 字段数值未增加,无法统计用户发布新闻总数。

2. 问题排查过程

  • 初步怀疑前端传参错误,userId固定为1;

  • 后端添加日志打印当前登录用户ID,测试非1用户(如id=2张三)发布新闻;

  • 日志输出userId正常,排除前端传参问题;

  • 确认用户ID由后端拦截器解析Token自动获取,无需前端传递。

3. 后端修复代码(NewsController addNews方法)

重构发布新闻接口,新增用户新闻数量自增逻辑,同步判断新闻新增、用户数据更新双状态,保证数据一致性:

 @Autowired
    private UserService userService;

    // 发布新闻
    @PostMapping("/add")
    public Result<?> addNews(@RequestBody NewsAddDTO dto) {
        // 1. 插入新闻
        Integer userId = UserContext.getCurrentUserId();
        System.out.println("当前用户ID:" + userId);
        if (userId == null) return Result.error("请先登录");
        News news = new News();
        news.setUserId(userId);
        news.setTitle(dto.getTitle());
        news.setContent(dto.getContent());
        news.setViewCount(0);
        boolean saved = newsService.save(news);
        // 2. 更新用户的 news_count + 1
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(User::getId, userId)
                .setSql("news_count = news_count + 1");
        boolean updated = userService.update(wrapper);

        if (saved && updated) {
            return Result.success("发布成功");
        } else {
            return Result.error("发布失败");
        }
    }

4. 修复结果

用户发布新闻后,user表 new_count 字段自动+1,新闻数量统计功能恢复正常。

课次36:前端全局样式统一优化

一、优化目标

统一项目页面UI风格,优化首页、发布页、注册页样式,解决页面风格杂乱问题,实现注册页与登录页样式完全统一、首页布局美化、发布页标题居中。

二、优化1:Home.vue 首页整体样式重构

1. 替换template结构

重构首页布局,拆分固定头部、滚动内容区、分页区,实现头部固定、内容可滚动的自适应布局,优化按钮、文本结构:

<!-- src/views/Home.vue -->
<template>
    <div class="home-container">
        <!-- 固定头部(新布局) -->
        <div class="header">
            <h2 class="title">微头条首页</h2>
            <div class="welcome">欢迎,{{ userStore.username }}</div>
            <div class="actions">
                <button class="publish-btn" @click="goToPublish">+ 发布微头条</button>
                <button class="logout-btn" @click="logout">退出登录</button>
            </div>
        </div>

        <!-- 可滚动的内容区域(新闻列表 + 分页) -->
        <div class="scroll-area">
            <div class="content-wrapper">
                <!-- 新闻列表 -->
                <div class="news-list">
                    <div v-if="newsList.length === 0" class="empty">
                        暂无新闻,快去发布一条吧
                    </div>
                    <div v-for="item in newsList" :key="item.id" class="news-item">
                        <h3>{{ item.title }}</h3>
                        <div class="time">{{ item.time }}</div>
                        <div class="content">{{ item.content }}</div>
                        <div class="actions">
                            <button @click="homeViewDetail(item.id)">🔍 查看详情</button>
                            <button @click="homeDeleteNews(item.id)">🗑️ 删除</button>
                            <button @click="homeLikeNews(item.id, item.likes)">👍 点赞 {{ item.likes }}</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-wrapper">
            <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :total="total"
                @current-change="loadNews" layout="prev, pager, next" />
        </div>
    </div>
</template>

2. 替换scoped样式

美化首页配色、卡片阴影、按钮hover效果、布局间距,适配全屏展示:

<style scoped>
/* 整体容器 */
.home-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: #f5f5f5;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* ===== 头部新布局 ===== */
.header {
    flex-shrink: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    background: #ffffff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    border-bottom: 1px solid #e8e8e8;
}

.header .title {
    margin: 0;
    color: #333;
    font-size: 20px;
    font-weight: 600;
}

/* 欢迎信息 – 居中显示,普通文本 */
.header .welcome {
    font-size: 16px;
    color: #555;
    /* 使用 flex:1 让它在剩余空间中居中 */
    flex: 1;
    text-align: center;
}

/* 右侧操作按钮组 */
.header .actions {
    display: flex;
    align-items: center;
    gap: 12px;
}

/* 统一按钮基础样式 */
.header .actions button {
    padding: 6px 18px;
    border: none;
    border-radius: 20px;
    font-size: 14px;
    cursor: pointer;
    transition: background 0.3s, transform 0.1s;
}

.header .actions button:hover {
    transform: scale(1.02);
}

/* 发布按钮 – 蓝色 */
.header .actions .publish-btn {
    background: #1890ff;
    color: white;
}

.header .actions .publish-btn:hover {
    background: #0c7bdf;
}

/* 退出按钮 – 红色 */
.header .actions .logout-btn {
    background: #ff4d4f;
    color: white;
}

.header .actions .logout-btn:hover {
    background: #ff7875;
}

/* ===== 滚动区域 ===== */
.scroll-area {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
}

.content-wrapper {
    max-width: 800px;
    margin: 0 auto;
}

/* ===== 新闻列表 ===== */
.news-list {
    margin-top: 0;
}

.news-item {
    background: white;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: transform 0.2s, box-shadow 0.2s;
}

.news-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.news-item h3 {
    margin: 0 0 8px 0;
    color: #333;
}

.time {
    font-size: 12px;
    color: #999;
    margin-bottom: 12px;
}

.content {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
    margin-bottom: 12px;
}

.actions button {
    margin-right: 10px;
    background: none;
    border: none;
    cursor: pointer;
    font-size: 14px;
    padding: 4px 8px;
    border-radius: 4px;
    transition: background 0.2s;
}

.actions button:first-child {
    color: #1890ff;
}

.actions button:nth-child(2) {
    color: #ff4d4f;
}

.actions button:last-child {
    color: #52c41a;
}

.actions button:hover {
    background: rgba(0, 0, 0, 0.04);
}

.empty {
    text-align: center;
    color: #999;
    padding: 40px;
}

/* 分页容器 */
.pagination-wrapper {
    flex-shrink: 0;
    display: flex;
    justify-content: center;
    padding: 16px 0 20px 0;
    background: #f5f5f5;
}
</style>

三、优化2:Publish.vue 发布页标题居中

在发布页面样式中新增标题居中CSS样式,优化页面视觉效果:

.publish-container h2 {
    margin-bottom: 20px;
    text-align: center;
}

四、优化3:Register.vue 注册页样式全局统一

完全重写注册页面代码,实现布局、配色、按钮、输入框样式与登录页面完全一致,统一项目UI风格:

<template>
    <div class="register-page">
        <div class="register-card">
            <h2>微头条注册</h2>

            <el-form :model="form" :rules="rules" ref="formRef" @keyup.enter="handleRegister">
                <el-form-item prop="username">
                    <el-input v-model="form.username" placeholder="用户名" clearable />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="form.password" type="password" placeholder="密码" clearable show-password />
                </el-form-item>
                <el-form-item prop="confirmPassword">
                    <el-input v-model="form.confirmPassword" type="password" placeholder="确认密码" clearable
                        show-password />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleRegister" :loading="loading" class="register-btn">
                        注册
                    </el-button>
                </el-form-item>
            </el-form>

            <div class="login-link">
                <router-link to="/login">已有账号?去登录</router-link>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { register } from '../api/user'
import { ElMessage } from 'element-plus'

const form = reactive({
    username: '',
    password: '',
    confirmPassword: ''
})

const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== form.password) {
                    callback(new Error('两次输入密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

const handleRegister = async () => {
    if (!formRef.value) return
    if (loading.value) return

    try {
        await formRef.value.validate()
        loading.value = true
        const res = await register({
            username: form.username,
            password: form.password
        })
        if (res.code === 200) {
            ElMessage.success('注册成功,请登录')
            router.push('/login')
        } else {
            ElMessage.error(res.message || '注册失败')
        }
    } catch (error) {
        if (error?.response?.data?.message) {
            ElMessage.error(error.response.data.message)
        } else if (error !== false) {
            ElMessage.error('请求失败,请检查网络')
        }
    } finally {
        loading.value = false
    }
}

onMounted(() => {
    document.body.style.overflow = 'hidden'
})

onUnmounted(() => {
    document.body.style.overflow = ''
})
</script>

<style scoped>
/* ===== 页面背景(与登录一致) ===== */
.register-page {
    height: 100vh;
    width: 100%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* ===== 卡片样式(完全复制登录页 .login-card) ===== */
.register-card {
    width: 360px;
    /* 与登录卡片宽度一致 */
    background: white;
    padding: 30px;
    border-radius: 16px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.register-card h2 {
    text-align: center;
    margin-bottom: 24px;
    color: #333;
}

/* ===== 覆盖 Element Plus 输入框样式,使其与原生 input 完全一致 ===== */
:deep(.el-input__wrapper) {
    padding: 0 12px;
    height: 40px; /* 与登录输入框高度一致(padding 12px + font-size 14px ≈ 40px) */
    border: 1px solid #ddd;
    border-radius: 8px;
    box-shadow: none !important;
    transition: border-color 0.2s;
}

:deep(.el-input__wrapper:hover) {
    box-shadow: none !important;
}

:deep(.el-input__wrapper.is-focus) {
    border-color: #667eea;
    box-shadow: none !important;
}

:deep(.el-input__inner) {
    height: 100%;
    line-height: 40px; /* 垂直居中 */
    font-size: 14px;
}

/* 表单每个输入框下方间距(与登录一致) */
:deep(.el-form-item) {
    margin-bottom: 16px;
}

/* ===== 覆盖 El-Button 样式,使其与登录按钮一致 ===== */
.register-btn {
    width: 100%;
    padding: 12px !important;
    height: 40px; /* 与输入框高度对齐 */
    border: none;
    border-radius: 8px;
    font-size: 16px;
    cursor: pointer;
    background-color: #667eea !important;
    color: white !important;
    transition: background 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
}

.register-btn:hover {
    background-color: #5a67d8 !important;
}

/* ===== 登录链接样式(与登录页一致) ===== */
.login-link {
    text-align: center;
    margin-top: 20px;
    font-size: 14px;
    color: #666;
}

.login-link a {
    color: #667eea;
    text-decoration: none;
}

.login-link a:hover {
    text-decoration: underline;
}
</style>

课次37:新闻详情功能开发与BUG修复

一、核心任务清单

  • 开发前端新闻详情页面,通过路由参数获取新闻ID,调用 /news/{id} 详情接口

  • 实现新闻详情展示、浏览量自增、作者权限判断、编辑/删除按钮权限控制

  • 修复详情页作者名称不显示的BUG

二、实操步骤1:新建新闻详情页 Detail.vue

创建 src/views/Detail.vue,实现详情展示、返回、编辑、删除、权限判断功能:

<template>
  <div class="detail-container">
    <el-card v-loading="loading">
      <template v-if="news">
        <h2>{{ news.title }}</h2>
        <div class="info">
          <span>作者:{{ news.authorName || '匿名' }}</span>
          <span>发布时间:{{ news.publishTime }}</span>
          <span>浏览量:{{ news.viewCount }}</span>
        </div>
        <div class="content">{{ news.content }}</div>
        <div class="actions">
          <el-button @click="$router.back()">返回首页</el-button>
          <el-button type="primary" @click="goToEdit" v-if="isOwner">编辑</el-button>
          <el-button type="danger" @click="handleDelete" v-if="isOwner">删除</el-button>
        </div>
      </template>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getNewsDetail, deleteNews } from '../api/news'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const news = ref(null)
const loading = ref(false)

const isOwner = computed(() => {
  return news.value && userStore.username && news.value.authorName === userStore.username
})

const loadDetail = async () => {
  loading.value = true
  try {
    const res = await getNewsDetail(route.params.id)
    if (res.code === 200) {
      news.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  } finally {
    loading.value = false
  }
}

const goToEdit = () => {
  router.push(`/edit/${news.value.id}`)
}

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定删除该新闻吗?', '提示', { type: 'warning' })
    const res = await deleteNews(news.value.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      router.push('/home')
    } else {
      ElMessage.error(res.message)
    }
  } catch {}
}

onMounted(loadDetail)
</script>

<style scoped>
.detail-container { max-width: 800px; margin: 40px auto; }
.info { color: #909399; font-size: 14px; margin: 16px 0; }
.info span { margin-right: 20px; }
.content { font-size: 16px; line-height: 1.8; margin: 20px 0; }
.actions { margin-top: 20px; }
</style>

三、实操步骤2:修复详情页作者名不显示BUG

1. 问题原因

后端新闻实体类未封装用户名返回字段,前端渲染字段与后端返回字段不匹配,导致作者名无法展示。

2. 后端修复:重写 getNewsDetail 方法

修改 NewsController 详情接口,查询新闻关联用户信息,封装用户名返回,同时实现浏览量自增:

    @GetMapping("/{id}")
    public Result<News> getNewsDetail(@PathVariable Integer id) {
        News news = newsService.getById(id);
        if (news != null) {
            // 增加浏览量
            news.setViewCount(news.getViewCount() + 1);
            newsService.updateById(news);
            // 关联查询用户,封装作者用户名
            User user = userService.getById(news.getUserId());
            news.setUserName(user.getUsername());
            return Result.success(news);
        } else {
            return Result.error("新闻不存在");
        }
    }

3. 前端修复:字段全局替换

打开 Detail.vue,使用全局替换快捷键 Ctrl+H,将所有 authorName 替换为 username,匹配后端返回字段。

4. 修复效果

新闻详情页可正常展示发布者用户名、发布时间、浏览量,数据展示完整无误。