400 Error despite working in Postman, possible reasons?

Viewed 154

I am using the Deepl API, and when I run the request in Postman it is successful, however using it in my app it returns only a 400 Error, which I assume means the headers aren't set up correctly, but it is just how it is in my Postman. Can anyone point out what may be the issue here?

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
1 Answers

The body property of a URL-encoded message (with the application/x-www-form-urlencoded content type) must be either a string of the query parameters, or a URLSearchParams instance.

Solution

  1. Pass the object of key/value pairs to the URLSearchParams constructor.
  2. You might as well add auth_key (one of the required query parameters) to that, and remove it from the URL.
  3. Remove JSON.stringify() from the text property as that would insert unnecessary quotes into the translation.
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'
  })
});
Related