-1

Here is the code I am working with:

const encodedParams = new URLSearchParams();
encodedParams.append("q", "Hello, world!");
encodedParams.append("target", "es");
encodedParams.append("source", "en");

const options = {
    method: 'POST',
    headers: {
        'content-type': 'application/x-www-form-urlencoded',
        'Accept-Encoding': 'application/gzip',
        'X-RapidAPI-Host': 'google-translate1.p.rapidapi.com',
        'X-RapidAPI-Key': '3955ade317mshe662a97591d523ap1e4475jsn3bb2b223ccbb'
    },
    body: encodedParams
};

fetch('https://google-translate1.p.rapidapi.com/language/translate/v2', options)
    .then(response => response.json())
    .then(response => console.log(response))
    .catch(err => console.error(err));

Here is the response I receive from the API

{data: {…}}
data:
translations: Array(1)
0: {translatedText: '¡Hola Mundo!'}
length: 1
[[Prototype]]: Array(0)
[[Prototype]]: Object
[[Prototype]]: Object

How would I grab the translatedText from the API response and set a variable equal to that. I have tried TRANSLATED_TEXT = response.data.translations[0].translatedText;.

I need to set a variable and then put the variable into a h1 on an HTML document. Any help with grabbing the API response would be appreciated!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    response data is available .... here `.then(response => console.log(response))` – Bravo Apr 28 '22 at 00:14
  • FYI the `content-type` header is [not required](https://stackoverflow.com/a/68643919/283366) when the body is an instance of `URLSearchParams` – Phil Apr 28 '22 at 00:22
  • try using async/await https://dmitripavlutin.com/javascript-fetch-async-await/ – Houssem Salem Apr 28 '22 at 00:28

2 Answers2

-1

try response.data.translations[0].translatedText.value;

or response.data.translations[0].translatedText[0].text;

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 28 '22 at 14:09
-1

Found a similar example: https://rapidapi.com/googlecloud/api/google-translate1/discussions/21334

Try: response.data.data['translations'][0]['translatedText']

Hope it helps.

Tin Po Chan
  • 97
  • 1
  • 3