Azure AI 文本翻译 REST API v3.0 实战:Node.js/Vue 项目 5 步集成,月免 2M 字符

发布时间:2026/7/8 12:43:38
Azure AI 文本翻译 REST API v3.0 实战:Node.js/Vue 项目 5 步集成,月免 2M 字符 Azure AI 文本翻译 REST API v3.0 实战Node.js/Vue 项目 5 步集成月免 2M 字符在全球化应用开发中多语言支持已成为标配需求。Azure AI 文本翻译服务作为微软认知服务家族的重要成员为开发者提供了高质量的机器翻译能力。本文将手把手带你完成从 Azure 资源创建到前端集成的完整流程特别适合已有 Node.js 和 Vue 基础的中级开发者。1. 环境准备与资源创建1.1 Azure 账户注册与资源创建首先需要访问 Azure 门户 完成服务开通在顶部搜索栏输入翻译工具点击创建按钮选择文本翻译填写基本信息时注意定价层选择免费 F0 层每月200万字符资源组建议新建专用资源组便于管理创建完成后进入资源获取关键信息# 关键参数示例实际值需替换 ENDPOINThttps://api.cognitive.microsofttranslator.com KEY1xxxxxxxxxxxxxxxxxxxxxxxxxxxx REGIONeastasia1.2 项目初始化对于 Vue 项目推荐使用 Vite 创建基础工程npm create vitelatest translation-demo --template vue-ts cd translation-demo npm install azure-rest/ai-translation-text2. 服务端封装Node.js2.1 创建安全代理接口为避免前端直接暴露密钥建议通过 Node.js 中间层转发请求// server/proxy.js import express from express; import { TextTranslationClient } from azure-rest/ai-translation-text; const app express(); app.use(express.json()); const client TextTranslationClient(process.env.ENDPOINT, { key: process.env.KEY1, region: process.env.REGION }); app.post(/translate, async (req, res) { try { const response await client.path(/translate).post({ body: req.body.texts, queryParameters: { to: req.body.to } }); res.json(response.body); } catch (error) { res.status(500).json({ error: error.message }); } }); app.listen(3000, () console.log(Proxy server running on port 3000));2.2 环境变量配置创建.env文件存储敏感信息ENDPOINThttps://api.cognitive.microsofttranslator.com KEY1your_primary_key_here REGIONeastasia提示务必在.gitignore中添加.env防止密钥泄露3. 前端集成Vue 33.1 创建翻译组件!-- src/components/TranslationForm.vue -- script setup langts import { ref } from vue; const inputText ref(); const targetLang ref(en); const result ref(); async function translate() { try { const response await fetch(http://localhost:3000/translate, { method: POST, headers: { Content-Type: application/json }, body: JSON.stringify({ texts: [{ text: inputText.value }], to: targetLang.value }) }); const data await response.json(); result.value data[0]?.translations[0]?.text || 翻译失败; } catch (error) { result.value 服务不可用; } } /script template div classtranslation-box textarea v-modelinputText placeholder输入要翻译的文本/textarea select v-modeltargetLang option valueen英语/option option valueja日语/option option valueko韩语/option /select button clicktranslate翻译/button div classresult{{ result }}/div /div /template3.2 样式优化添加基础样式提升用户体验.translation-box { max-width: 600px; margin: 0 auto; padding: 20px; } textarea { width: 100%; height: 100px; margin-bottom: 10px; } .result { margin-top: 20px; padding: 15px; border: 1px solid #eee; min-height: 50px; }4. 高级功能实现4.1 多语言批量翻译修改代理接口支持多文本翻译// 在原有路由后添加 app.post(/batch-translate, async (req, res) { const { texts, from, to } req.body; const promises texts.map(text client.path(/translate).post({ body: [{ text }], queryParameters: { from, to } }) ); try { const results await Promise.all(promises); res.json(results.map(r r.body[0].translations[0].text)); } catch (error) { res.status(500).json({ error: error.message }); } });4.2 语言检测添加语言检测端点app.post(/detect, async (req, res) { try { const response await client.path(/detect).post({ body: [{ text: req.body.text }] }); res.json(response.body[0]); } catch (error) { res.status(500).json({ error: error.message }); } });5. 部署与优化5.1 生产环境配置创建config/prod.js区分环境module.exports { endpoint: process.env.ENDPOINT, credentials: { key: process.env.KEY1, region: process.env.REGION }, rateLimit: { windowMs: 15 * 60 * 1000, // 15分钟 max: 100 // 每个IP限制100次请求 } };5.2 性能优化技巧缓存策略对相同内容的翻译结果进行缓存const cache new Map(); app.post(/translate, async (req, res) { const cacheKey ${req.body.texts}_${req.body.to}; if (cache.has(cacheKey)) { return res.json(cache.get(cacheKey)); } // ...原有逻辑 cache.set(cacheKey, response.body); });错误重试机制async function withRetry(fn, retries 3) { try { return await fn(); } catch (error) { if (retries 0) throw error; await new Promise(res setTimeout(res, 1000)); return withRetry(fn, retries - 1); } }监控指标添加基础性能监控app.use((req, res, next) { const start Date.now(); res.on(finish, () { console.log(${req.method} ${req.url} - ${Date.now() - start}ms); }); next(); });在实际项目中我发现合理设置超时时间能显著提升用户体验。特别是在移动网络环境下建议前端设置 5-8 秒的超时阈值并给出友好的等待提示。对于企业级应用可以考虑使用 Azure API 管理服务来获得更好的流量控制和监控能力。