恒美微站
首页
关于我们
建站服务
主题模板
案例展示
资讯中心
联系我们
新手友好!50 行代码封装 DeepSeek API,快速搭建 AI 对话网页
首页
资讯中心
/
新手友好!50 行代码封装 DeepSeek API,快速搭建 AI 对话网页
新手友好!50 行代码封装 DeepSeek API,快速搭建 AI 对话网页
发布时间:2026/8/26 17:17:20
新手友好50 行代码封装 DeepSeek API快速搭建 AI 对话网页新手友好50 行代码封装 DeepSeek API快速搭建 AI 对话网页一、最终效果二、为什么不用复杂框架三、准备工作四、50 行核心代码封装 DeepSeek 聊天接口五、前端页面输入消息并展示回复六、调用原理讲清楚1. 前端不能直接放 API Key2. messages 是什么3. 为什么项目里要保留 history4. DeepSeek 为什么能用 OpenAI SDK七、开源项目 JXL-AI 做了哪些增强八、总结新手友好50 行代码封装 DeepSeek API快速搭建 AI 对话网页本文适合刚接触 AI API、想做一个自己的 AI 聊天网页、但又不想一上来就被框架和工程配置劝退的新手。最近很多同学都想给自己的个人网站、课程作业或者小工具接入 AI 对话功能。其实最小闭环并不复杂前端输入一句话后端转发给 DeepSeek API拿到回复后再返回给前端展示。我做了一个开源项目JXL-AI用原生 Node.js 原生 HTML/CSS/JS 搭了一个 AI 对话网页同时保留了图鉴上传、排行榜、小游戏等扩展功能。项目地址https://github.com/Tuoxie423/jxl-ai在线体验https://tuoxie.asia/如果你觉得项目对新手有帮助欢迎点一个 Star 支持一下。一、最终效果项目里有几个页面首页角色展示、小游戏、排行榜、证书生成聊天页调用 DeepSeek API 和角色对话图鉴页上传图片并展示开场动画页角色入场动画README 里放了截图和 GIFclone 后可以直接运行npminstallnpmstart浏览器访问http://127.0.0.1:5177二、为什么不用复杂框架很多 AI Web 教程一上来就是Next.jsLangChain向量数据库登录系统云函数部署这些当然都很强但对新手来说有点重。这篇文章只讲最小闭环浏览器输入消息 ↓ fetch 请求自己的 Node 后端 ↓ Node 后端调用 DeepSeek API ↓ DeepSeek 返回 AI 回复 ↓ 后端把 reply 返回给浏览器 ↓ 页面展示回复只要理解这个流程你再去学复杂框架就会轻松很多。三、准备工作你需要Node.js 22.5推荐 Node.js 24一个 DeepSeek API Key一个普通编辑器安装依赖npminstallopenai配置环境变量不要把 Key 写死到代码里exportDEEPSEEK_API_KEY你的 DeepSeek API KeyWindows PowerShell$env:DEEPSEEK_API_KEY你的 DeepSeek API Key四、50 行核心代码封装 DeepSeek 聊天接口下面是最小可运行版本保存为server.mjsimport{createServer}fromnode:http;import{readFileSync,existsSync,createReadStream}fromnode:fs;importpathfromnode:path;importOpenAIfromopenai;constport5177;constpublicDirpath.resolve(public);constclientnewOpenAI({baseURL:https://api.deepseek.com,apiKey:process.env.DEEPSEEK_API_KEY});constservercreateServer(async(req,res){consturlnewURL(req.url,http://${req.headers.host});if(req.methodPOSTurl.pathname/api/chat){constbodyawaitreadBody(req);constinputJSON.parse(body||{});constmessageString(input.message||).trim();if(!message){sendJson(res,400,{error:message_required});return;}constcompletionawaitclient.chat.completions.create({model:deepseek-chat,messages:[{role:system,content:你是一个友好的中文 AI 助手。},{role:user,content:message}]});constreplycompletion.choices?.[0]?.message?.content||我刚刚走神了。;sendJson(res,200,{reply});return;}constfileurl.pathname/?index.html:url.pathname.slice(1);constfilePathpath.join(publicDir,file);if(!existsSync(filePath)){res.writeHead(404);res.end(Not found);return;}createReadStream(filePath).pipe(res);});server.listen(port,(){console.log(http://127.0.0.1:${port});});functionreadBody(req){returnnewPromise(resolve{constchunks[];req.on(data,chunkchunks.push(chunk));req.on(end,()resolve(Buffer.concat(chunks).toString(utf8)));});}functionsendJson(res,status,data){constbodyJSON.stringify(data);res.writeHead(status,{Content-Type:application/json; charsetutf-8});res.end(body);}上面代码做了三件事创建一个 Node HTTP 服务暴露/api/chat接口收到用户消息后调用 DeepSeek API再把回复返回给前端五、前端页面输入消息并展示回复新建public/index.html!doctypehtmlhtmllangzh-CNheadmetacharsetutf-8metanameviewportcontentwidthdevice-width, initial-scale1titleDeepSeek AI 聊天 Demo/titlestylebody{margin:0;min-height:100vh;display:grid;place-items:center;font-family:system-ui,Microsoft YaHei,sans-serif;background:#f6efe1;}main{width:min(720px,calc(100vw - 32px));padding:24px;border:2px solid #222;border-radius:12px;background:#fffaf0;box-shadow:10px 10px 0rgba(0,0,0,.12);}#messages{min-height:320px;display:grid;gap:12px;align-content:start;margin-bottom:16px;}.msg{padding:12px 14px;border:2px solid #222;border-radius:10px;background:white;}.user{background:#f3d886;justify-self:end;}form{display:flex;gap:10px;}input{flex:1;padding:12px;border:2px solid #222;border-radius:8px;}button{padding:0 18px;border:2px solid #222;border-radius:8px;background:#222;color:white;}/style/headbodymainh1DeepSeek AI 聊天 Demo/h1dividmessages/divformidforminputidinputplaceholder输入一句话试试button发送/button/form/mainscriptconstformdocument.getElementById(form);constinputdocument.getElementById(input);constmessagesdocument.getElementById(messages);functionaddMessage(text,type){constdivdocument.createElement(div);div.classNamemsg${type};div.textContenttext;messages.appendChild(div);}form.addEventListener(submit,asyncevent{event.preventDefault();consttextinput.value.trim();if(!text)return;addMessage(text,user);input.value;addMessage(思考中...,bot);constlastmessages.lastElementChild;try{constresawaitfetch(/api/chat,{method:POST,headers:{Content-Type:application/json},body:JSON.stringify({message:text})});constdataawaitres.json();last.textContentdata.reply||没有拿到回复;}catch{last.textContent请求失败请检查后端服务。;}});/script/body/html运行nodeserver.mjs打开http://127.0.0.1:5177到这里一个最小 AI 对话网页就跑起来了。六、调用原理讲清楚很多新手会卡在“API 到底是怎么调的”。其实可以把它理解成一次普通的 HTTP 请求。1. 前端不能直接放 API Key错误做法fetch(https://api.deepseek.com/...,{headers:{Authorization:Bearer 你的 Key}});这样 Key 会暴露在浏览器里任何人打开开发者工具都能看到。正确做法浏览器 → 你的 Node 后端 → DeepSeek APIAPI Key 只放在后端环境变量中。2. messages 是什么DeepSeek/OpenAI 兼容接口使用messages数组表示对话上下文messages:[{role:system,content:你是一个友好的中文 AI 助手。},{role:user,content:你好}]常见 rolerole作用system设定 AI 的身份、语气、规则user用户说的话assistantAI 之前回复过的话如果你想让 AI 记住上下文就把最近几轮user和assistant一起发给模型。3. 为什么项目里要保留 history单轮对话用户你好 AI你好呀多轮对话用户我叫小明 AI你好小明 用户我叫什么 AI你叫小明模型本身不会自动记住上一次请求所以需要前端或后端保存历史再传给 API。项目里的聊天页就是把最近几轮 history 发给后端后端再拼进messagesconstmessages[{role:system,content:你是佳小乐一个温暖、机灵、会鼓励用户的中文互动角色。},...history.slice(-10),{role:user,content:userMessage}];4. DeepSeek 为什么能用 OpenAI SDKDeepSeek 提供了 OpenAI 兼容接口所以可以这样写constclientnewOpenAI({baseURL:https://api.deepseek.com,apiKey:process.env.DEEPSEEK_API_KEY});关键点是SDK 还是openaibaseURL换成 DeepSeekapiKey换成 DeepSeek 的 Keymodel使用 DeepSeek 支持的模型名七、开源项目 JXL-AI 做了哪些增强上面的 Demo 是最小版而我的开源项目 JXL-AI 在它基础上做了完整网页AI 角色聊天页聊天失败时本地回复兜底开场动画图片投稿图鉴SQLite 排行榜同名用户确认整活证书生成Nginx/PM2 部署友好项目结构. ├── server.mjs ├── package.json ├── data/app.db ├── public/ │ ├── index.html │ ├── chat.html │ ├── intro.html │ ├── bestiary.html │ ├── uploads/ │ └── assets/ └── scripts/check.mjs八、总结AI 对话网页的核心并不神秘本质就是前端收集输入 后端保护 API Key 后端请求 DeepSeek 前端展示回复先跑通这个最小闭环再去加角色设定、历史上下文、上传、数据库、部署就会顺很多。我把完整项目开源了https://github.com/Tuoxie423/jxl-ai如果这篇文章或项目帮你跑通了第一个 AI 网页欢迎给项目点一个 Star。后续我也会继续更新更多适合新手的 AI Web 实战内容。