'POST https://google-translate1.p.rapidapi.com/language/translate/v2 502 (Bad Gateway) When fetching in React

An example of the rapidapi google translate API code for the JavaScript fetch method is:

fetch("https://google-translate1.p.rapidapi.com/language/translate/v2", {
"method": "POST",
"headers": {
"x-rapidapi-host": "google-translate1.p.rapidapi.com",
"x-rapidapi-key": "MY-API-KEY",
"accept-encoding": "application/gzip",
"content-type": "application/x-www-form-urlencoded"
},
"body": {
"source": "en",
"q": "Hello, world!",
"target": "es"
}
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
})

Now I copied it, and used it for the React component as follows:

fetch("https://google-translate1.p.rapidapi.com/language/translate/v2", {
method: "POST",
body: {
"source": "en",
"q": "Hello, world!",
"target": "es"
},
headers: {
"x-rapidapi-host": "google-translate1.p.rapidapi.com",
"x-rapidapi-key": "MY-API-KEY",
"accept-encoding": "application/gzip",
"content-type": "application/x-www-form-urlencoded"
}
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
})

After running the program, I get the error "POST https://google-translate1.p.rapidapi.com/language/translate/v2 502 (Bad Gateway)" on the console!

How can I have a healthy connection to the server?



Solution 1:[1]

this code solved the same problem for me

    <script>
    const key = "your key"
      const qs = obj => {
      return new URLSearchParams(obj).toString();
      }
      const word = "Hello, world";
      const data = qs({
      q: word,
      source: "en",
      target: "es",
      })

      const options = {
      method: "POST",
      url: "https://google-translate1.p.rapidapi.com/language/translate/v2",
      headers: {
      "content-type": "application/x-www-form-urlencoded",
      "x-rapidapi-key": key,
      "x-rapidapi-host": "google-translate1.p.rapidapi.com",
      },
      data: data,
      };
      axios.request(options).then(function (response) {
      console.log(response.data);
      })
      .catch(function (error) {
      console.error(99, error);
      });
    </script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1