【问题标题】:400 Error despite working in Postman, possible reasons?尽管在 Postman 工作,但出现 400 错误,可能的原因是什么?
【发布时间】:2021-12-24 02:57:50
【问题描述】:

我正在使用 Deepl API,当我在 Postman 中运行请求时它是成功的,但是在我的应用程序中使用它只返回 400 错误,我认为这意味着标头设置不正确,但它我的邮递员就是这样。谁能指出这里可能是什么问题?

async translateMessage(data = {}) {
  const url = "https://api.deepl.com/v2/translate?auth_key=myAuthKey";
  const response = await fetch(url, {
    method: "POST",
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': '*/*'
    },
    body: {
      text: JSON.stringify(this.text),
      target_lang: 'DE',
      source_lang: 'EN'
    }
  });
  return response.json();
},

Example HTTP Post Request from Documentation:

POST /v2/translate?auth_key=[yourAuthKey]> HTTP/1.0
Host: api.deepl.com
User-Agent: YourApp
Accept: */*
Content-Length: [length]
Content-Type: application/x-www-form-urlencoded

auth_key=[yourAuthKey]&text=Hello, world&source_lang=EN&target_lang=DE

【问题讨论】:

  • this.text 只是一个字符串吗?您是否尝试过不先将其转换为 JSON?
  • 正如@BradyHolt 提到的,如果您检查来自AJAX 调用的线路,一个区别是由于JSON.stringify,它会发送额外的引号。它可能类似于auth_key=[yourAuthKey]&text="Hello, world"&source_lang=EN&target_lang=DE。为什么不比较发送的实际标头而不是 AJAX 调用?
  • @BradyHolt 如果我简单地使用 - text: this.text, - 它给我提供了同样的错误。
  • @JuanMendes 抱歉,我不知道“电线”指的是什么。删除 JSON.stringify 也没有奏效。它也没有在网络开发工具选项卡中发送任何内容。
  • Dev tools' network tab shows you the request 出去了,或者如果你真的需要原始请求,你可以使用wireshark.org 之类的东西。

标签: javascript vue.js vuejs2


【解决方案1】:

URL 编码消息(内容类型为application/x-www-form-urlencoded)的body 属性必须是查询参数字符串或URLSearchParams 实例。

解决方案

  1. 将键/值对的对象传递给URLSearchParams 构造函数。
  2. 您不妨在其中添加auth_key(必需的查询参数之一),然后将其从 URL 中删除。
  3. text 属性中删除JSON.stringify(),因为这会在翻译中插入不必要的引号。
const url = 'https://api.deepl.com/v2/translate';
const response = await fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': '*/*'
  },            1️⃣
  body: new URLSearchParams({
    auth_key: myAuthKey, 2️⃣
    text: this.text, 3️⃣
    target_lang: 'DE',
    source_lang: 'EN'
  })
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 2018-09-01
    • 2013-06-25
    • 2020-06-27
    • 1970-01-01
    • 2021-12-26
    • 2011-11-18
    相关资源
    最近更新 更多