Vue + Express + DeepSeek 实现一个简单的对话式 AI 应用(2026 最新版教程)
这个教程将手把手教你构建一个简单的实时聊天 AI 应用:
- 前端:Vue 3(Composition API + Script Setup) + Bootstrap 美化
- 后端:Express.js(Node.js)代理 DeepSeek API(避免前端暴露 API Key)
- AI 模型:DeepSeek-V3.2(最新版本,base URL: https://api.deepseek.com,模型: deepseek-chat 或 deepseek-reasoner)
功能:
- 用户输入消息 → 发送到后端 → 调用 DeepSeek API → 返回回复
- 支持聊天历史显示
- 支持流式响应(实时打字效果,可选)
为什么用后端代理?前端直接调用会暴露 API Key,不安全。
前置准备
- 获取 DeepSeek API Key:
- 访问 https://platform.deepseek.com/api_keys
- 注册/登录 → 创建 API Key(sk- 开头)
- 安装 Node.js(v18+):https://nodejs.org/
- 项目结构:
ai-chat-app/
├── backend/ # Express 后端
│ ├── server.js
│ └── package.json
└── frontend/ # Vue 3 前端
├── src/
│ ├── App.vue
│ ├── main.js
│ └── components/Chat.vue
├── public/
└── package.json
步骤 1:创建 Express 后端(backend 文件夹)
mkdir ai-chat-app && cd ai-chat-app
mkdir backend && cd backend
npm init -y
npm install express axios cors dotenv
package.json(添加启动脚本):
"scripts": {
"start": "node server.js"
}
.env(存放 Key,不要提交到 Git):
DEEPSEEK_API_KEY=sk-your-real-key-here
DEEPSEEK_BASE_URL=https://api.deepseek.com
DEEPSEEK_MODEL=deepseek-chat // 或 deepseek-reasoner(思考模式)
server.js:
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
const PORT = 3000;
app.use(cors()); // 允许前端跨域
app.use(express.json());
app.post('/api/chat', async (req, res) => {
const { messages } = req.body; // [{role: 'user', content: 'hello'}]
try {
const response = await axios.post(
`${process.env.DEEPSEEK_BASE_URL}/chat/completions`,
{
model: process.env.DEEPSEEK_MODEL,
messages: messages,
stream: false // 可改为 true 支持流式(需前端处理 SSE)
},
{
headers: {
'Authorization': `Bearer ${process.env.DEEPSEEK_API_KEY}`,
'Content-Type': 'application/json'
}
}
);
const aiReply = response.data.choices[0].message.content;
res.json({ reply: aiReply });
} catch (error) {
console.error(error.response?.data || error.message);
res.status(500).json({ error: 'AI 服务错误' });
}
});
app.listen(PORT, () => {
console.log(`后端运行在 http://localhost:${PORT}`);
});
启动后端:npm start
步骤 2:创建 Vue 3 前端(frontend 文件夹)
cd ../
npx create-vue@latest frontend
# 选择:TypeScript? No, JSX? No, Vue Router? No, Pinia? No, Vitest? No, ESLint? Yes
cd frontend
npm install axios bootstrap
src/main.js(引入 Bootstrap):
import { createApp } from 'vue'
import App from './App.vue'
import 'bootstrap/dist/css/bootstrap.min.css'
createApp(App).mount('#app')
src/App.vue(简单布局):
<template>
<div class="container mt-5">
<h1 class="text-center mb-4">DeepSeek AI 聊天机器人</h1>
<Chat />
</div>
</template>
<script>
import Chat from './components/Chat.vue'
export default {
components: { Chat }
}
</script>
src/components/Chat.vue(核心聊天组件):
<template>
<div class="card">
<div class="card-body" style="height: 60vh; overflow-y: auto;">
<div v-for="(msg, index) in messages" :key="index" class="mb-3">
<strong>{{ msg.role === 'user' ? '你' : 'AI' }}:</strong>
<p class="border rounded p-2" :class="{'bg-light': msg.role === 'user', 'bg-info text-white': msg.role === 'assistant'}">
{{ msg.content }}
</p>
</div>
<div v-if="loading" class="text-center">AI 思考中...</div>
</div>
<div class="card-footer">
<form @submit.prevent="sendMessage" class="d-flex">
<input v-model="input" class="form-control me-2" placeholder="输入消息..." required />
<button type="submit" class="btn btn-primary" :disabled="loading">发送</button>
</form>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
import axios from 'axios'
const messages = ref([])
const input = ref('')
const loading = ref(false)
async function sendMessage() {
if (!input.value.trim()) return
messages.value.push({ role: 'user', content: input.value })
const userMessage = input.value
input.value = ''
loading.value = true
try {
const res = await axios.post('http://localhost:3000/api/chat', {
messages: [...messages.value, { role: 'user', content: userMessage }]
})
messages.value.push({ role: 'assistant', content: res.data.reply })
} catch (err) {
messages.value.push({ role: 'assistant', content: '出错啦,请重试' })
} finally {
loading.value = false
}
}
</script>
启动前端:npm run dev(默认 http://localhost:5173)
步骤 3:运行与测试
- 先启动后端:
cd backend && npm start - 再启动前端:
cd frontend && npm run dev - 浏览器打开前端页面,开始聊天!
效果:输入消息 → 点击发送 → DeepSeek 返回智能回复,历史记录显示。
扩展建议(进阶)
- 流式响应:后端设置
stream: true,返回 SSE,前端用 EventSource 实时显示打字效果。 - 聊天历史持久化:加数据库(如 MongoDB)。
- 部署:前端用 Vercel/Netlify,后端用 Render/Heroku。
- 模型切换:用
deepseek-reasoner开启思考模式(更强推理)。
这个应用简单高效,适合学习全栈 AI 开发!代码已完整可运行。
如果需要流式版本、添加登录、或打包部署指南,随时告诉我,我继续帮你完善~🚀