You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Vue3+Vite5项目中使用deepl-node遇http.Agent构造函数错误

问题:Vue3 + Vite项目中使用deepl-node报错http.Agent is not a constructor

我在基于Vite 5.0.11的Vue 3项目中使用deepl-node包,代码完全按照官方示例编写:

import * as deepl from 'deepl-node';

const authKey = "---"; // 替换为你的密钥
const translator = new deepl.Translator(authKey);

(async () => {
    const result = await translator.translateText('Hello, world!', null, 'fr');
    console.log(result.text); // Bonjour, le monde !
})();

运行后抛出以下错误:

deepl-node.js?v=2f8c41fd:2475 Uncaught TypeError: http.Agent is not a constructor
    at node_modules/deepl-node/dist/client.js (deepl-node.js?v=2f8c41fd:2475:18)
    at __require (chunk-P2LSHJDD.js?v=45007535:4:50)
    at node_modules/deepl-node/dist/index.js (deepl-node.js?v=2f8c41fd:3021:20)
    at __require (chunk-P2LSHJDD.js?v=45007535:4:50)
    at deepl-node.js?v=2f8c41fd:3566:16
node_modules/deepl-node/dist/client.js @ deepl-node.js?v=2f8c41fd:2475
__require @ chunk-P2LSHJDD.js?v=45007535:4
node_modules/deepl-node/dist/index.js @ deepl-node.js?v=2f8c41fd:3021
__require @ chunk-P2LSHJDD.js?v=45007535:4
(anonymous) @ deepl-node.js?v=2f8c41fd:3566
Show 5 more frames
Show less

原因及解决办法

原因

deepl-node是仅适用于Node.js环境的包,它依赖Node.js内置的http/https模块及其中的Agent类,浏览器环境中没有这些API,直接在Vue前端代码中使用必然报错。另外,将deepl密钥放在前端代码中会导致密钥泄露,存在安全风险。

解决办法

1. 将翻译逻辑移至后端(推荐)

  • 搭建Node.js后端服务,在后端中使用deepl-node处理翻译请求
  • 前端通过Axios等工具向后端发送请求,传递待翻译文本,后端返回翻译结果
  • 示例后端代码(Express框架):
const express = require('express');
const deepl = require('deepl-node');
const app = express();
const port = 3001;

const authKey = "你的deepl密钥";
const translator = new deepl.Translator(authKey);

app.use(express.json());

app.post('/translate', async (req, res) => {
    const { text, targetLang } = req.body;
    try {
        const result = await translator.translateText(text, null, targetLang);
        res.json({ translatedText: result.text });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

app.listen(port, () => {
    console.log(`翻译服务运行在 http://localhost:${port}`);
});
  • 前端调用示例:
import axios from 'axios';

async function translateText(text, targetLang) {
    try {
        const response = await axios.post('http://localhost:3001/translate', {
            text,
            targetLang
        });
        return response.data.translatedText;
    } catch (error) {
        console.error('翻译失败:', error);
    }
}

// 使用
translateText('Hello, world!', 'fr').then(result => console.log(result));

2. 使用浏览器兼容的翻译方案

如果不想搭建后端,可以使用deepl提供的浏览器端API(需通过官方申请),或其他支持浏览器环境的翻译库。但无论哪种方式,都要注意密钥的安全管理,避免直接暴露在前端代码中。

内容的提问来源于stack exchange,提问作者demiglace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 11:23:15