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

Postman调用Deepl API正常但应用内返回400错误的原因排查

问题根因

  • Content-Type 设置为 application/x-www-form-urlencoded 时,fetch 不支持直接传入普通对象作为请求体。你的写法中请求体最终会被转为 [object Object] 的无效字符串,完全不符合DeepL API的格式要求,是触发400错误的核心原因。
  • 多余的文本序列化操作:你对this.text执行了JSON.stringify处理,会导致文本内容被额外套上双引号,比如原始文本hello会被转为"hello",即便请求调通也会得到不符合预期的翻译结果。
  • 冗余参数问题:你将auth_key放在URL参数中,按官方规范放在请求体或者URL中二选一即可,不会直接触发报错但不符合最佳实践。

修正后的代码

async translateMessage(data = {}) {
  const url = "https://api.deepl.com/v2/translate";
  // 构造符合urlencoded格式要求的请求体
  const requestBody = new URLSearchParams({
    auth_key: "替换为你的真实auth_key",
    text: this.text,
    target_lang: 'DE',
    source_lang: 'EN'
  });
  const response = await fetch(url, {
    method: "POST",
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': '*/*'
    },
    body: requestBody
  });
  return response.json();
}

如果运行环境不支持URLSearchParams,可以手动拼接编码后的请求体字符串:

const requestBody = `auth_key=替换为你的真实auth_key&text=${encodeURIComponent(this.text)}&target_lang=DE&source_lang=EN`

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:45:08