【问题标题】:POST request to DeepL api through node.js not working通过 node.js 对 DeepL api 的 POST 请求不起作用
【发布时间】:2021-07-17 18:21:37
【问题描述】:

谁能发现任何可以解释为什么 api 客户端给我禁止错误的问题?我知道凭据是正确的,因为 GET 请求在 url 工作中找到了相同的信息。

提前谢谢你

 app.get('/translate', (req, res) => {
    var textToTranslate = "Hello friend"
    const targetLanguage = "ES"
    var link = `https://api-free.deepl.com/v2/translate`

    var options = 
    {
      method: 'POST',
      headers: {
        "Host": 'api-free.deepl.com',
        "Content-Length": 54,
        "Content-Type": 'application/x-www-form-urlencoded',
        "User-Agent": "YourApp",
        "Accept": "*/*",

      },
      body: JSON.stringify({
        'auth_key': deeplAccessCode,
        'text': textToTranslate,
        'target_lang': targetLanguage
    }),
    }

  
    return fetch(link, options)
      .then((response) => {
        console.log(response)
        return response.json(); //Transform http body to json
      })
        .then((json)=> {
          res.send(json) //return json to browser
        })
        .catch(e => {
          console.log(e)
          return res.sendStatus(400);
          });
  })

【问题讨论】:

    标签: node.js json http fetch


    【解决方案1】:

    它可能会失败,因为您将身体的Content-Type 设置为application/x-www-form-urlencoded(根据DeepL API specification 是正确的),但随后您提供了一个 JSON 正文(这需要内容类型为 @ 987654325@)。

    您需要提供一个 URL 编码的正文,例如您也可以在 ? 之后附加到 URL 的部分。另请参阅 SO 上的 this answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-15
      • 2018-03-05
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多