Nuxt.js全栈高手养成指南:从零到高并发实战,手把手打通SSR+国内生态部署+大厂级架构

文章目录

阶段一:基础认知与快速上手

1:什么是Nuxt.js?为什么你需要它?

1.1 Nuxt.js 的定位

Nuxt.js 是一个基于 Vue.js 的 全栈开发框架(注意:不是“库”),它的核心目标是简化 Vue 应用的开发流程,尤其擅长解决以下问题:

  • 服务端渲染 (SSR):让 Vue 应用拥有更好的 SEO 和首屏加载速度。
  • 静态站点生成 (SSG):将页面预渲染为静态 HTML,适合博客、文档站等。
  • 自动化配置:自动生成路由、代码拆分、优化构建配置,开发者只需专注写代码。

1.2 与 Vue.js 的关系

  • Vue.js 是核心:Nuxt.js 底层依赖 Vue.js,所有 Vue 的语法和特性(组件、响应式、指令等)在 Nuxt 中完全适用。
  • Nuxt.js 是扩展:它在 Vue 基础上添加了“约定大于配置”的目录结构、服务端渲染能力、模块化插件系统等高级功能。

1.3 核心特性

(1) 渲染模式自由切换
模式描述适用场景
SSR (Server-Side Rendering)服务器实时生成 HTML 发送给浏览器需要 SEO 的动态网站(电商、新闻站)
SSG (Static Site Generation)构建时预生成静态 HTML内容固定的站点(博客、企业官网)
SPA (Single Page Application)纯客户端渲染对 SEO 无要求的后台管理系统
(2) 自动路由系统
  • 无需手动配置路由:只需在 pages/ 目录下创建 .vue 文件,Nuxt 会自动生成路由。
  • 示例:创建 pages/about.vue → 自动生成 /about 路由。
(3) 模块化开发
  • 官方/社区模块:一键集成 Axios(HTTP 请求)、Pinia(状态管理)、Tailwind CSS 等工具。
  • 配置简单:在 nuxt.config.js 中声明模块即可。

1.4 何时选择 Nuxt.js?

场景推荐方案
需要 SEO 优化的内容型网站Nuxt.js (SSR/SSG)
纯后台管理系统(无需 SEO)直接使用 Vue.js (SPA)
需快速搭建企业官网Nuxt.js (SSG) + 内容管理系统(如 WordPress)

2:10分钟创建你的第一个Nuxt项目

2.1 环境准备

步骤 1:安装 Node.js
  • 访问 Node.js 官网 下载 LTS 版本(如 v18.x)。
  • 安装后验证是否成功:
    node -v  # 应输出版本号(如 v18.16.0)
    npm -v   # 应输出版本号(如 9.5.1)
    
步骤 2:选择包管理工具(npm 或 yarn)
  • 如果喜欢更快的速度,可安装 Yarn:
    npm install -g yarn
    yarn -v  # 验证版本
    

2.2 创建 Nuxt 项目

步骤 1:使用脚手架
npx create-nuxt-app my-first-nuxt-app
  • 如果使用 Yarn:
    yarn create nuxt-app my-first-nuxt-app
    
步骤 2:回答交互式问题

以下是推荐小白选择的配置(方向键选择,回车确认):

? Programming language: JavaScript
? Package manager: Npm 或 Yarn(根据上一步选择)
? UI framework: None (先不用 UI 库,避免复杂度)
? Nuxt.js modules: None (后续手动添加)
? Linting tools: None (先跳过代码检查)
? Testing framework: None
? Rendering mode: Universal (SSR / SSG)
? Deployment target: Server (SSR)
? Development tools: jsconfig.json (可选)
? Continuous integration: None
? Version control system: Git
步骤 3:启动开发服务器
cd my-first-nuxt-app
npm run dev  # 或 yarn dev
  • 访问 http://localhost:3000,你会看到默认欢迎页!
步骤 4:体验热重载 (Hot Reload)
  • 打开 pages/index.vue,修改 <h1> 标签内的文字。
  • 保存文件,浏览器会自动刷新显示最新内容。

3:解剖Nuxt项目结构

3.1 关键目录与文件

my-first-nuxt-app/
├── pages/          # 页面组件,自动生成路由
├── layouts/        # 布局组件(如页头、页脚)
├── assets/         # 静态资源(CSS/图片/字体)
├── components/     # 可复用的 Vue 组件
├── nuxt.config.js  # Nuxt 配置文件
└── package.json    # 项目依赖和脚本

3.2 核心文件详解

(1) pages/index.vue
<template>
  <div>
    <h1>Welcome to Nuxt!</h1>
  </div>
</template>
  • 这是你的首页组件,对应路由 /
(2) layouts/default.vue
<template>
  <div>
    <NuxtPage />  <!-- 页面内容将插入此处 -->
  </div>
</template>
  • 默认布局,所有页面默认使用此布局。
  • <NuxtPage /> 是页面内容的占位符。
(3) nuxt.config.js
export default {
  // 配置 Nuxt 的核心选项
  modules: [],     // 添加模块
  css: [],         // 全局 CSS 文件
  buildModules: [],// 开发环境模块
}

阶段二:页面开发与路由基础

1. 创建你的第一个页面

步骤 1:新建 about 页面
  1. pages/ 目录下创建 about.vue 文件:
    <template>
      <div>
        <h1>关于我们</h1>
        <p>这里是关于页面的内容。</p>
      </div>
    </template>
    
  2. 保存文件后,访问 http://localhost:3000/about,页面自动生效!
步骤 2:理解自动路由规则
文件路径生成的路由地址
pages/index.vue/
pages/about.vue/about
pages/blog/index.vue/blog
pages/users/_id.vue/users/:id

2. 使用组件实现代码复用

步骤 1:创建公共组件
  1. components/ 下新建 Header.vue
    <template>
      <header>
        <nav>
          <NuxtLink to="/">首页</NuxtLink>
          <NuxtLink to="/about">关于</NuxtLink>
        </nav>
      </header>
    </template>
    
    <style scoped>
    nav { padding: 20px; background: #f0f0f0; }
    a { margin-right: 15px; }
    </style>
    
步骤 2:在页面中引入组件

修改 pages/index.vue

<template>
  <div>
    <Header /> <!-- 使用组件 -->
    <h1>Welcome to Nuxt!</h1>
  </div>
</template>

<script>
import Header from '@/components/Header.vue' // 导入组件

export default {
  components: { Header } // 注册组件
}
</script>

3. 动态路由实战

步骤 1:创建动态路由页面
  1. pages/ 下新建 users/_id.vue(注意下划线前缀):
    <template>
      <div>
        <h1>用户详情页</h1>
        <p>用户ID:{{ $route.params.id }}</p>
      </div>
    </template>
    
  2. 访问 http://localhost:3000/users/123,页面显示用户ID:123。
步骤 2:使用 <NuxtLink> 跳转

Header.vue 中添加链接:

<NuxtLink to="/users/456">用户456</NuxtLink>

4. 布局系统精讲

步骤 1:自定义布局
  1. 创建 layouts/custom.vue
    <template>
      <div>
        <Header />
        <main>
          <slot /> <!-- 页面内容插入点 -->
        </main>
        <footer style="margin-top: 50px; text-align: center;">
          <p>© 2023 我的网站</p>
        </footer>
      </div>
    </template>
    
    <script>
    import Header from '@/components/Header.vue'
    
    export default {
      components: { Header }
    }
    </script>
    
步骤 2:指定页面使用布局

修改 pages/about.vue

<script>
export default {
  layout: 'custom' // 使用自定义布局
}
</script>

5. 导航组件进阶

使用 <NuxtLink> 的激活类
  1. 修改 Header.vue 样式:
    .nuxt-link-active {
      font-weight: bold;
      color: #42b983;
    }
    
  2. 当前路由对应的链接会自动添加 nuxt-link-active 类。

本阶段练习任务

  1. 创建一个 /contact 页面,展示联系方式。
  2. 实现动态路由 /posts/:slug,显示文章标题。
  3. 为所有页面添加全局页脚(通过默认布局修改)。

阶段三:数据获取与状态管理

1. 数据获取的两种核心方式

Nuxt.js 提供两种异步数据获取方法:asyncData(服务端获取)和 fetch(客户端或服务端获取)。

(1) asyncData:服务端数据预获取
  • 特性:在页面渲染前运行(服务端),SEO 友好。
  • 适用场景:需要 SEO 的页面数据(如商品详情页)。
  • 示例:在 pages/posts/_id.vue 中:
    <template>
      <div>
        <h1>{{ post.title }}</h1>
        <p>{{ post.content }}</p>
      </div>
    </template>
    
    <script>
    export default {
      async asyncData({ params }) {
        // 模拟 API 请求
        const post = await $fetch(`https://api.example.com/posts/${params.id}`)
        return { post } // 返回的数据会合并到组件 data 中
      }
    }
    </script>
    
(2) fetch:客户端或服务端获取
  • 特性:可以在客户端或服务端运行,适合非关键数据。
  • 示例:在 pages/index.vue 中:
    <script>
    export default {
      data() {
        return { products: [] }
      },
      async fetch() {
        this.products = await $fetch('https://api.example.com/products')
      }
    }
    </script>
    

2. 使用 Axios 发送 HTTP 请求

步骤 1:安装 Axios 模块
npm install @nuxtjs/axios
步骤 2:配置 nuxt.config.js
export default {
  modules: ['@nuxtjs/axios'],
  axios: {
    baseURL: 'https://api.example.com' // 基础 URL
  }
}
步骤 3:在组件中使用
<script>
export default {
  async asyncData({ $axios }) {
    const users = await $axios.$get('/users')
    return { users }
  }
}
</script>

3. 状态管理:Pinia 入门

Pinia 是 Vue 官方推荐的状态管理库,替代 Vuex。

步骤 1:安装 Pinia
npm install @pinia/nuxt
步骤 2:配置 nuxt.config.js
export default {
  modules: ['@pinia/nuxt']
}
步骤 3:创建 Store
  1. 新建 stores/counter.js
    import { defineStore } from 'pinia'
    
    export const useCounterStore = defineStore('counter', {
      state: () => ({ count: 0 }),
      actions: {
        increment() {
          this.count++
        }
      }
    })
    
步骤 4:在组件中使用
<template>
  <div>
    <button @click="counter.increment">点击次数:{{ counter.count }}</button>
  </div>
</template>

<script>
import { useCounterStore } from '~/stores/counter'

export default {
  setup() {
    const counter = useCounterStore()
    return { counter }
  }
}
</script>

4. 数据缓存与错误处理

(1) 使用 useAsyncData (Nuxt 3)
<script setup>
const { data, error } = await useAsyncData('posts', () => {
  return $fetch('https://api.example.com/posts')
})

if (error.value) {
  console.error('数据加载失败:', error.value)
}
</script>
(2) 全局错误页面
  1. 创建 layouts/error.vue
    <template>
      <div class="error-container">
        <h1 v-if="error.statusCode === 404">页面不存在</h1>
        <h1 v-else>发生错误:{{ error.message }}</h1>
        <NuxtLink to="/">返回首页</NuxtLink>
      </div>
    </template>
    
    <script>
    export default {
      props: ['error']
    }
    </script>
    

本阶段练习任务

  1. 创建一个 /news 页面,从公开 API(如 NewsAPI)获取新闻列表并渲染。
  2. 实现一个购物车功能:通过 Pinia 管理商品添加/删除状态。
  3. 在动态路由页 /posts/:id 中添加加载状态提示和错误边界处理。

阶段四:部署与性能优化(国内版)

1. 国内主流部署方案

(1) 静态站点部署(SSG)

适用场景:博客、企业官网、文档站等静态内容。
推荐平台

  • 阿里云 OSS(对象存储)
  • 腾讯云 COS(对象存储)
  • Gitee Pages(码云静态托管,适合开源项目)
  • 七牛云 Kodo
(2) 服务端渲染部署(SSR)

适用场景:动态网站(电商、社交平台)。
推荐平台

  • 阿里云 ECS(云服务器)
  • 腾讯云 CVM(云服务器)
  • 华为云弹性云服务器
  • Serverless 服务(阿里云函数计算、腾讯云 SCF)

2. 静态站点部署实战(以阿里云 OSS 为例)

步骤 1:生成静态文件
  1. 修改 nuxt.config.js
    export default {
      target: 'static' // 指定生成静态站点
    }
    
  2. 构建并生成静态文件:
    npm run generate
    
    • 产物会生成在 dist/ 目录。
步骤 2:上传到阿里云 OSS
  1. 创建 OSS Bucket
    • 登录 阿里云控制台,创建 Bucket,选择「公共读」权限。
    • 地域选择离用户近的(如华东1-杭州)。
  2. 上传文件
    • 在 OSS 控制台进入 Bucket,点击「上传文件」,将 dist/ 目录下的所有内容上传。
    • 或使用命令行工具 ossutil
      ossutil cp -r dist/ oss://你的Bucket名称/ --recursive
      
  3. 绑定自定义域名(可选):
    • 在 Bucket 的「域名管理」中绑定已备案的域名,并配置 CDN 加速。

3. 服务端渲染部署实战(以腾讯云 CVM 为例)

步骤 1:服务器准备
  1. 购买腾讯云 CVM 实例(推荐 CentOS 或 Ubuntu 系统)。
  2. 通过 SSH 连接服务器:
    ssh root@你的服务器IP
    
步骤 2:部署 Node.js 环境
  1. 安装 Node.js 和 npm:
    # Ubuntu/Debian
    curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
    sudo apt install -y nodejs
    
    # CentOS
    curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
    sudo yum install -y nodejs
    
步骤 3:部署 Nuxt 项目
  1. 将代码上传到服务器(使用 Git 或 SFTP 工具)。
  2. 安装依赖并构建:
    npm install
    npm run build
    
  3. 使用 PM2 守护进程:
    npm install pm2 -g
    pm2 start "npm run start" --name nuxt-app
    

4. 国内性能优化技巧

(1) 图片优化
  • 使用腾讯云数据万象(CI)
    • 自动压缩、格式转换、缩略图生成。
    • nuxt.config.js 中配置图片域名:
      export default {
        image: {
          domains: ['你的Bucket.ci.tencentcloudcs.com']
        }
      }
      
  • 懒加载
    <NuxtImg src="image.jpg" loading="lazy" />
    
(2) CDN 加速
  • 阿里云 CDN腾讯云 CDN
    • 将静态资源(JS/CSS/图片)托管到 CDN,提升访问速度。
    • nuxt.config.js 中配置资源路径:
      export default {
        build: {
          publicPath: 'https://你的CDN域名/_nuxt/'
        }
      }
      
(3) 代码压缩与合并
  • 启用 Brotli 压缩(需服务器支持):
    // nuxt.config.js
    export default {
      build: {
        compress: {
          brotli: true,
          gzip: true
        }
      }
    }
    
(4) 缓存策略
  • OSS/COS 设置缓存头
    • 在对象存储控制台为静态文件设置 Cache-Control: max-age=31536000(1年)。
  • API 请求缓存
    // 使用内存缓存
    const cachedData = useState('data', () => null)
    if (!cachedData.value) {
      cachedData.value = await $fetch('/api/data')
    }
    

5. 国内监控与分析工具

  • 性能监测
    • 阿里云 ARMS(应用实时监控)
    • 腾讯云前端性能监控(RUM)
  • SEO 分析
    • 百度统计友盟+
  • 错误追踪
    • Sentry 国内版(https://sentry.cn)

本阶段练习任务

  1. 将 Nuxt 项目部署到 Gitee Pages(需关联码云仓库并开启 Pages 服务)。
  2. 使用 腾讯云数据万象 对首页图片进行压缩和 WebP 格式转换。
  3. 通过 阿里云 CDN 加速静态资源,对比加速前后的加载速度。

阶段五:进阶实战与生态集成

1. 中间件(Middleware):路由守卫与权限控制

(1) 什么是中间件?
  • 定义:在页面渲染前执行的代码,用于全局或页面级的逻辑处理(如身份验证、日志记录)。
  • 运行环境:服务端(SSR)或客户端(SPA)。
(2) 实战:实现登录拦截
  1. 创建中间件文件
    在根目录新建 middleware/auth.js

    export default function ({ redirect, store }) {
      // 假设 Pinia 存储用户状态
      if (!store.auth.isLoggedIn) {
        return redirect('/login') // 未登录跳转到登录页
      }
    }
    
  2. 应用中间件

    • 全局生效(在 nuxt.config.js 中配置):
      export default {
        router: { middleware: ['auth'] }
      }
      
    • 页面级生效(在页面组件中):
      <script>
      export default {
        middleware: 'auth' // 仅当前页面生效
      }
      </script>
      

2. 插件开发:扩展 Nuxt 能力

(1) 封装 Axios 拦截器(适配国内常见鉴权)
  1. 创建插件文件 plugins/axios.js

    export default function ({ $axios, store }) {
      $axios.onRequest(config => {
        // 添加腾讯云鉴权头部(示例)
        config.headers['X-Signature'] = store.auth.token
        return config
      })
    
      $axios.onError(error => {
        if (error.response.status === 401) {
          // Token 过期跳转登录
          window.location.href = '/login?expired=1'
        }
        return Promise.reject(error)
      })
    }
    
  2. 注册插件
    nuxt.config.js 中:

    export default {
      plugins: ['@/plugins/axios']
    }
    
(2) 集成微信 JS-SDK
  1. 安装依赖

    npm install weixin-js-sdk
    
  2. 创建插件 plugins/wx-sdk.js

    import wx from 'weixin-js-sdk'
    
    export default ({ app }, inject) => {
      inject('wx', wx) // 全局注入 this.$wx
    }
    

3. TypeScript 深度支持

(1) 启用 TypeScript
  1. 安装依赖

    npm install @nuxt/typescript-build @nuxt/types --save-dev
    
  2. 配置 nuxt.config.js

    export default {
      buildModules: ['@nuxt/typescript-build']
    }
    
  3. 创建类型声明文件 types/index.d.ts

    import { User } from '~/types/user'
    
    declare module '@nuxt/types' {
      interface Context {
        $auth: User // 扩展上下文类型
      }
    }
    
(2) 类型化 Pinia Store

修改 stores/counter.ts

import { defineStore } from 'pinia'

interface CounterState {
  count: number
}

export const useCounterStore = defineStore('counter', {
  state: (): CounterState => ({ count: 0 }),
  actions: {
    increment() {
      this.count++
    }
  }
})

4. 集成国内 UI 框架:Vant

(1) 安装与配置
  1. 安装 Vant

    npm install vant @vant/auto-import-resolver
    
  2. 配置 nuxt.config.js

    export default {
      buildModules: [
        ['@nuxtjs/vuetify', { autoImport: true }] // 自动按需引入
      ],
      css: ['vant/lib/index.css']
    }
    
(2) 在组件中使用
<template>
  <van-button type="primary" @click="submit">提交</van-button>
</template>

<script>
// 无需手动导入,自动引入!
export default {
  methods: {
    submit() { /* ... */ }
  }
}
</script>

5. 百度 SEO 优化实战

(1) 自动生成 sitemap
  1. 安装模块

    npm install @nuxtjs/sitemap
    
  2. 配置 nuxt.config.js

    export default {
      modules: ['@nuxtjs/sitemap'],
      sitemap: {
        hostname: 'https://你的域名.com',
        routes: async () => {
          // 动态生成路由(如从 API 获取)
          return ['/about', '/contact']
        }
      }
    }
    
(2) 百度主动推送

nuxt.config.js 中添加:

export default {
  head: {
    script: [
      {
        src: 'https://zz.bdstatic.com/linksubmit/push.js', // 百度推送 JS
        async: true
      }
    ]
  }
}

本阶段练习任务

  1. 开发一个中间件:实现管理员权限控制(/admin 路由仅允许 admin 角色访问)。
  2. 封装插件:为 Axios 添加腾讯云 API 的公共参数签名逻辑。
  3. TypeScript 改造:将已有 Vue 组件转换为 TypeScript,并定义接口类型。
  4. Vant 实战:使用 Vant 组件构建移动端注册表单。

阶段六:全栈开发与微服务架构

1. 全栈架构设计

(1) 技术选型
模块国内推荐方案
前端Nuxt.js (SSR) + Vant(移动端) / Element Plus(PC端)
后端Nest.js(企业级) / Midway.js(阿里云生态) / Egg.js(阿里系)
数据库MySQL(阿里云 RDS) / MongoDB(腾讯云 MongoDB)
云服务阿里云 Serverless(函数计算 + API 网关) / 腾讯云云开发(TCB)
部署容器化(阿里云 ACK / 腾讯云 TKE) + CDN 加速

2. 实战:Nuxt.js + Midway.js 全栈开发

(1) 后端服务搭建(Midway.js)
  1. 初始化项目

    npm init midway@latest -y
    

    选择 koa-v3 模板。

  2. 创建商品查询接口
    src/controller/product.controller.ts

    import { Controller, Get, Inject } from '@midwayjs/core'
    import { Context } from '@midwayjs/koa'
    
    @Controller('/api/product')
    export class ProductController {
      @Inject()
      ctx: Context
    
      @Get('/:id')
      async getProduct(): Promise<any> {
        const id = this.ctx.params.id
        // 模拟数据库查询
        return { code: 200, data: { id, name: `商品${id}`, price: 99.9 } }
      }
    }
    
  3. 本地运行

    npm run dev
    

    访问 http://localhost:7001/api/product/123 测试接口。


(2) 前端 Nuxt.js 集成
  1. 配置代理解决跨域
    nuxt.config.js

    export default {
      modules: ['@nuxtjs/axios'],
      axios: {
        proxy: true // 开启代理
      },
      proxy: {
        '/api/': {
          target: 'http://localhost:7001',
          pathRewrite: { '^/api/': '' }
        }
      }
    }
    
  2. 页面调用接口
    pages/product/_id.vue

    <template>
      <div>
        <h1>{{ product.name }}</h1>
        <p>价格:{{ product.price }}元</p>
      </div>
    </template>
    
    <script>
    export default {
      async asyncData({ $axios, params }) {
        const { data } = await $axios.get(`/api/product/${params.id}`)
        return { product: data }
      }
    }
    </script>
    

3. 微服务架构实战(阿里云函数计算)

(1) 将 Midway 后端部署为 Serverless
  1. 安装 Serverless 工具

    npm install @midwayjs/serverless-scf -g
    
  2. 配置 f.yml

    service:
      name: nuxt-demo-backend
    
    provider:
      name: aliyun
      region: cn-hangzhou
    
    functions:
      product:
        handler: product.default
        events:
          - http:
              path: /api/product/{id}
              method: get
    
  3. 部署到阿里云

    midway deploy
    

(2) 前端对接云函数

修改 nuxt.config.js 代理配置:

proxy: {
  '/api/': {
    target: 'https://你的云函数网关地址',
    pathRewrite: { '^/api/': '' }
  }
}

4. 微前端架构集成(qiankun)

(1) 主应用配置(Nuxt.js)
  1. 安装 qiankun

    npm install qiankun -S
    
  2. 主应用入口插件 plugins/qiankun.js

    import { registerMicroApps, start } from 'qiankun'
    
    export default ({ app }) => {
      registerMicroApps([
        {
          name: 'vue-subapp',
          entry: '//子应用域名/subapp/',
          container: '#subapp-container',
          activeRule: '/subapp'
        }
      ])
      start()
    }
    
  3. 在布局中添加容器

    <template>
      <div id="main-app">
        <Header />
        <div id="subapp-container"></div>
      </div>
    </template>
    

(2) 子应用(Vue.js)适配
  1. 导出生命周期钩子
    subapp/src/public-path.js

    if (window.__POWERED_BY_QIANKUN__) {
      __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__
    }
    
  2. 修改入口文件

    import './public-path'
    import Vue from 'vue'
    import App from './App.vue'
    
    let instance = null
    
    function render(props = {}) {
      const { container } = props
      instance = new Vue({
        render: h => h(App)
      }).$mount(container ? container.querySelector('#app') : '#app')
    }
    
    // 独立运行时
    if (!window.__POWERED_BY_QIANKUN__) {
      render()
    }
    
    export async function bootstrap() {}
    export async function mount(props) { render(props) }
    export async function unmount() { instance.$destroy() }
    

5. 持续集成与部署(CI/CD)

(1) 使用 GitLab CI 自动化部署
  1. 编写 .gitlab-ci.yml

    stages:
      - build
      - deploy
    
    cache:
      paths:
        - node_modules/
    
    build_frontend:
      stage: build
      image: node:16
      script:
        - npm install
        - npm run generate
      artifacts:
        paths:
          - dist/
    
    deploy_oss:
      stage: deploy
      image: alpine
      script:
        - apk add --no-cache python3 py3-pip
        - pip install oss2
        - python3 deploy_oss.py  # 自定义上传脚本
    
  2. 阿里云 OSS 上传脚本 deploy_oss.py

    import oss2
    
    auth = oss2.Auth('你的AK', '你的SK')
    bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'bucket名称')
    
    for root, dirs, files in os.walk('dist'):
        for file in files:
            local_path = os.path.join(root, file)
            remote_path = local_path.replace('dist/', '')
            bucket.put_object_from_file(remote_path, local_path)
    

本阶段练习任务

  1. 全栈实战:基于 Nuxt + Midway 实现一个商品管理系统(增删改查)。
  2. 微服务拆分:将用户模块拆分为独立云函数并集成。
  3. 微前端改造:将后台管理模块作为子应用接入 qiankun 主应用。
  4. CI/CD 实战:配置 GitLab CI 实现自动部署到阿里云 OSS。

阶段七:性能调优与安全加固

一、性能调优进阶

1. 服务端性能优化

国内场景痛点:高并发访问、南北网络延迟差异
解决方案

  • (1) 服务端渲染缓存(SSR Cache)

    // nuxt.config.js
    export default {
      render: {
        http2: { push: true }, // 开启 HTTP/2 推送
        static: { maxAge: 1000 * 60 * 60 * 24 }, // 静态资源缓存
        cdn: { 
          use: true, // 启用 CDN
          domain: 'https://你的阿里云CDN域名' 
        }
      }
    }
    
  • (2) 使用 Redis 缓存热点数据

    // 阿里云 Redis 连接示例(需安装 ioredis)
    import Redis from 'ioredis'
    
    const redis = new Redis({
      host: '阿里云Redis实例地址',
      port: 6379,
      password: '你的密码'
    })
    
    // Nuxt 插件中缓存接口数据
    export default async ({ $axios }, inject) => {
      inject('cacheGet', async (key, url) => {
        const cached = await redis.get(key)
        if (cached) return JSON.parse(cached)
        const data = await $axios.$get(url)
        await redis.setex(key, 3600, JSON.stringify(data)) // 缓存1小时
        return data
      })
    }
    
2. 客户端性能优化

国内场景痛点:弱网环境、低端安卓设备兼容性
解决方案

  • (1) 首屏关键 CSS 内联

    // nuxt.config.js
    export default {
      build: {
        extractCSS: { 
          ignoreOrder: true,
          inline: ['app.css'] // 内联关键 CSS
        }
      }
    }
    
  • (2) 按需加载第三方库(如高德地图)

    // plugins/amap.js
    export default ({ app }, inject) => {
      inject('loadAMap', () => {
        return new Promise((resolve) => {
          if (window.AMap) return resolve(window.AMap)
          const script = document.createElement('script')
          script.src = 'https://webapi.amap.com/maps?v=2.0&key=你的高德地图Key'
          script.onload = () => resolve(window.AMap)
          document.head.appendChild(script)
        })
      })
    }
    
3. 数据库优化

国内云服务集成

  • 阿里云 PolarDB(兼容 MySQL,自动弹性扩展)
  • 腾讯云 TDSQL-C(Serverless 数据库)
    优化技巧
-- 示例:添加索引提升查询速度
ALTER TABLE products 
ADD INDEX idx_category_status (category_id, status);

二、安全加固实战

1. 基础安全防护

(1) HTTPS 强制跳转

  • 国内免费 SSL 证书
    • 阿里云 SSL 证书(免费 DV 版)
    • 腾讯云 TrustAsia 免费证书
  • Nginx 配置
    server {
      listen 80;
      server_name yourdomain.com;
      return 301 https://$server_name$request_uri;
    }
    

(2) 防止 XSS 攻击

  • CSP 内容安全策略
    // nuxt.config.js
    export default {
      head: {
        meta: [
          { 
            'http-equiv': 'Content-Security-Policy',
            content: `default-src 'self' https://*.aliyuncs.com; script-src 'self' 'unsafe-inline' https://unpkg.com`
          }
        ]
      }
    }
    
2. 接口安全防护

(1) CSRF Token 校验

// 使用 @nuxtjs/axios 模块配置
export default {
  axios: {
    credentials: true,
    baseURL: process.env.API_BASE_URL,
    proxyHeaders: false,
    retry: { retries: 3 }
  },
  modules: ['@nuxtjs/axios'],
  // 生成 CSRF Token
  serverMiddleware: [
    { path: '/api/csrf', handler: '~/server-middleware/csrf.js' }
  ]
}

(2) 敏感数据脱敏

// 使用中间件过滤敏感字段
export default function ({ res }) {
  res.setHeader('X-Content-Type-Options', 'nosniff')
  res.setHeader('X-XSS-Protection', '1; mode=block')
}
3. 防爬虫与 CC 攻击

国内工具推荐

  • 阿里云 WAF(Web 应用防火墙)
  • 腾讯云天御防爬服务
    配置示例
// 在 Nuxt 中识别爬虫并拦截
export default function (req, res, next) {
  const userAgent = req.headers['user-agent']
  const isBot = /bot|spider|crawl|scraping/i.test(userAgent)
  if (isBot) {
    res.statusCode = 403
    return res.end('Forbidden')
  }
  next()
}

三、合规与监控

1. 等保 2.0 合规要求
  • 日志留存:使用阿里云日志服务(SLS)存储 6 个月以上
  • 审计追踪:接入阿里云 ActionTrail
  • 数据加密:启用阿里云 KMS 密钥管理
2. 实时监控方案

国内推荐组合

  • 前端监控:阿里云前端监控(FMP)
  • 错误追踪:Sentry 国内版(sentry.io)
  • API 监控:腾讯云 APM

配置示例(阿里云 FMP)

// nuxt.config.js
export default {
  head: {
    script: [
      { 
        src: 'https://g.alicdn.com/sd/sentry/loader/your-sdk.js',
        async: true,
        onload: `Sentry.init({ dsn: '你的DSN' })`
      }
    ]
  }
}

四、实战练习

  1. 性能调优

    • 将 SSR 页面接入阿里云 CDN,对比首屏加载时间
    • 使用 Chrome Performance 工具分析并优化一个低性能页面
  2. 安全加固

    • 申请免费 SSL 证书并配置 HTTPS 强制跳转
    • 为敏感接口添加 CSRF Token 校验
  3. 合规改造

    • 配置阿里云 WAF 防御 SQL 注入攻击
    • 接入 Sentry 国内版实现错误监控


阶段八:大厂级项目实战复盘——电商平台全栈开发

一、项目背景与需求

1. 业务场景
  • 目标:开发一个符合国内电商业务特点的全栈应用,支持高并发、高可用、安全合规。
  • 核心功能
    • 商品展示(SSR 渲染 + CDN 加速)
    • 用户体系(手机号登录 + 微信授权)
    • 订单管理(状态机设计)
    • 支付系统(微信支付 + 支付宝)
    • 实时通知(WebSocket + 短信推送)
2. 技术选型
模块国内技术栈
前端Nuxt.js (SSR) + Vant UI + 高德地图(物流追踪)
后端Midway.js (阿里系) + MySQL(阿里云 RDS) + Redis(阿里云 KVStore)
支付微信支付(JSAPI) + 支付宝(手机网站支付)
部署阿里云 ACK(容器服务) + SLB(负载均衡) + 日志服务(SLS)
监控阿里云 ARMS(应用监控) + 云盾(安全防护)

二、项目架构设计

1. 架构图
用户浏览器 → 阿里云 CDN(缓存静态资源) → 阿里云 SLB → Nuxt 服务集群(SSR)
                          ↓
                   Midway 微服务集群(订单/支付/商品)
                          ↓
                  阿里云 RDS(MySQL) + Redis(缓存/分布式锁)
2. 微服务拆分
服务名称功能描述技术实现
商品服务商品详情、搜索、分类Midway.js + MySQL
订单服务下单、支付状态回调、超时关闭Midway.js + Redis 分布式锁
用户服务登录、权限管理、地址簿Midway.js + JWT
支付服务聚合微信/支付宝支付、对账Midway.js + 微信支付 SDK

三、实战开发步骤

1. 商品模块开发(SSR 极致优化)

(1) 商品详情页 SSR 缓存

// nuxt.config.js
export default {
  render: {
    ssrCache: {
      max: 1000, // 缓存 1000 个页面
      ttl: 60 * 1000 // 缓存 1 分钟
    }
  }
}

(2) 图片懒加载 + WebP 自动转换

<template>
  <NuxtImg 
    src="/product.jpg" 
    :modifiers="{ format: 'webp' }" 
    loading="lazy" 
    provider="aliyun" 
  />
</template>
2. 用户认证(国内手机号+微信)

(1) 短信登录(阿里云 SMS)

// Midway 控制器
@Post('/sms/login')
async smsLogin(@Body() { phone, code }) {
  const cacheCode = await redis.get(`sms:${phone}`)
  if (code !== cacheCode) throw new Error('验证码错误')
  const user = await userService.findOrCreate(phone)
  return { token: generateJWT(user.id) }
}

(2) 微信授权登录

// Nuxt 插件
export default ({ app }, inject) => {
  inject('wechatLogin', () => {
    const appId = '你的公众号AppID'
    const redirectUri = encodeURIComponent('https://你的域名/auth/wechat')
    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo`
  })
}
3. 订单支付(微信+支付宝聚合)

(1) 微信支付统一下单

// Midway 支付服务
async createWechatPay(order) {
  const result = await wxpay.unifiedOrder({
    body: order.title,
    out_trade_no: order.no,
    total_fee: order.amount * 100,
    openid: order.user.openid
  })
  return {
    paymentUrl: result.mweb_url,
    paySign: result.sign
  }
}

(2) 支付结果回调校验

@Post('/pay/notify/wechat')
async wechatNotify(@Body() xmlData) {
  const result = await wxpay.verifySign(xmlData)
  if (result.return_code === 'SUCCESS') {
    await orderService.completePayment(result.out_trade_no)
  }
  return '<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>'
}

四、部署与运维

1. 容器化部署(阿里云 ACK)

(1) Dockerfile 配置

FROM node:16-alpine

WORKDIR /app
COPY . .
RUN npm install --production
RUN npm run build

EXPOSE 3000
CMD ["npm", "start"]

(2) Kubernetes 部署文件

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nuxt-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nuxt
  template:
    metadata:
      labels:
        app: nuxt
    spec:
      containers:
      - name: nuxt
        image: registry.cn-hangzhou.aliyuncs.com/your-repo/nuxt-app:latest
        ports:
        - containerPort: 3000
2. 监控与告警

(1) 阿里云 ARMS 接入

// 前端监控(Nuxt 插件)
export default ({ app }, inject) => {
  if (process.client) {
    const BrowserLogger = require('alife-logger').Browser
    const __bl = BrowserLogger.singleton({
      pid: '你的项目ID',
      appType: 'web',
      imgUrl: 'https://arms-retcode.aliyuncs.com/r.png'
    })
    inject('arms', __bl)
  }
}

(2) 异常告警规则

  • 指标:HTTP 错误率 > 5%
  • 动作:短信 + 钉钉群通知

五、项目复盘总结

1. 关键技术点
  • SSR 缓存策略:通过页面级缓存扛住 5000+ QPS
  • 支付对账系统:每日定时任务核对微信/支付宝账单
  • 分布式锁设计:使用 Redis 防止超卖
2. 典型问题与解决
问题场景解决方案
微信支付 NAT 穿透失败使用阿里云 EIP 绑定服务器 + 支付回调域名备案
首屏加载白屏时间长关键 CSS 内联 + 图片 WebP 转换 + 阿里云 DCDN 全站加速
恶意刷单攻击接入阿里云 WAF + 滑动验证码(行为验证)
3. 扩展练习
  • 秒杀系统:接入 RocketMQ 消息队列 + Redis 原子计数器
  • 物流追踪:集成快递鸟 API + 高德地图轨迹绘制
  • 数据大屏:ECharts 实时展示订单量/用户地域分布

全文完

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值