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
相关产品推荐
相关产品推荐

