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

DeepL API长文本翻译失效求助:短文本正常长文本无翻译

问题排查与修复方案

核心问题原因

你手动对text字段执行了encodeURIComponent编码,但axios在发送application/x-www-form-urlencoded类型请求时,会自动对请求参数做URL编码,这就导致文本被双重编码。短文本因字符简单未触发异常,而长文本包含空格、特殊字符时,双重编码后的内容无法被DeepL API正确解析,因此直接返回原文本。

修复步骤

修改translateText函数,移除手动编码和解码操作即可解决问题:

// Function to translate the text
async function translateText(text, sourceLang, targetLang) {
    try {
        // 移除手动encodeURIComponent,交由axios自动处理参数编码
        const requestData = {
            text: text,
            source_lang: sourceLang,
            target_lang: targetLang,
        };

        const response = await axios.post(
            'https://api-free.deepl.com/v2/translate',
            requestData,
            {
                headers: {
                    Authorization: `DeepL-Auth-Key ${deepLAuthKey}`,
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
            }
        );

        // 移除decodeURIComponent,直接使用API返回的原始翻译文本
        const translatedText = response.data.translations[0].text;
        return translatedText;
    } catch (error) {
        console.error('Translation error:', error.response?.data || error.message);
        throw error;
    }
}

额外优化建议

  • 在catch块中打印error.response.data,可以查看DeepL API返回的具体错误信息,更精准定位后续问题;
  • 确认你的API密钥处于正常可用状态,免费版API有字符量限制,但当前问题与该限制无关。

内容的提问来源于stack exchange,提问作者Diogo Gonçalves

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 10:52:41