I created an account via cloud for Google Translate, created an API key and got the credentials information. Api url works without any problems in Postman. I also created a react.js web project to test it and it works fine there too. However, when I integrate my React Native application, it gives an error and terminates the session in my application. I log in to my chat application again and try it, the same thing continues. [enter image description here](https://i.sstatic.net/8nLEsBTK.png)
const handleTranslate = async () => {
try {
const translatedConfessionText = await translateText(
selectedConfession.confess,
);
const translatedTitle = await translateText(selectedConfession.title);
setTranslatedConfessionText(translatedConfessionText);
setTranslatedTitle(translatedTitle);
} catch (error) {
console.error('Error translating text:', error);
}
};
const translateText = async text => {
try {
const response = await axios.post(
'https://translation.googleapis.com/language/translate/v2?key=********',
{
q: text,
source: 'tr',
target: 'en',
},
);
return response.data.data.translations[0].translatedText;
} catch (error) {
console.error('Error translating text:', error.response.data);
throw error;
}
};
<Text style={styles.modalText}>
{translatedConfessionText || selectedConfession?.confess}
</Text>
There is no problem with web or postman.
enter image description here
2
Answers
I tried the same api url link by creating a new react native project and it does not give an error there. I didn't make any changes on the google cloud side either.
This application translates without errors with the same URL.
const API_URL = "https://translation.googleapis.com/language/translate/v2?key=******";
const translateText = async (text, targetLanguage) => { const response = await axios.post(
${API_URL}
, { q: text, target: targetLanguage, });return response.data.data.translations[0].translatedText; };
export default translateText;
This is indeed curious.
It’s confusing that Google provides 2 endpoints
translation
/translate
And the documentation (Supported Features) for
translation.googleapis.com
Basic v2 does include that it supports API Keys but I think it (no longer) does.The Translating text (Basic) documentation includes a REST example that requires a
POST
method and requires OAuth:So, I think you should definitely consider using a Client SDK (includes auth too) rather than raw REST but, I think (!?) you’ll need to consider using OAuth (per the error message) and see Set up authentication