简体   繁体   中英

jQuery Google Translate 403 Error on translation call

I'm trying to make a call to google translate, I use my google API key and I keep getting a 403 error cant seem to figure out. I think I'm using the proper script type HTML tag "application/javascript" cant seem to figure this out

This is the error in the chrome console:

GET https://www.googleapis.com/language/translate/v2?key=API KEY REMOVED&source=en&target=de&q=How%20are%20you 403

   send @ jquery.min.js:2
   ajax @ jquery.min.js:2
   S.<computed> @ jquery.min.js:2
   translatePage @ (index):26
   onclick @ (index):17

using this code:

<html>
  <body>
  <head>
    <script type="application/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
   
   <b>Text:</b> <input type="text" id="text" value="How are you"/> <br>
    <b>Target Langugage:</b> 
    <select id="target">
    <option value="de">Germany</option>
    <option value="hi">Hindi</option>
    <option value="fr">French</option>
    </select>
    
    <br>
    
    <input type="button" value="Translate"  onclick="translatePage()" />
    
    <br> <br>
    
    <b>Translated Text:</b><div id="translated"></div>   
    
    <script>
    function translatePage()
    {
        $.get("https://www.googleapis.com/language/translate/v2",
            {
            key:"GOOGLE API KEY",
            source:"en",
            target:$("#target").val(),
            q:$("#text").val()
            },
            function(response)
            {
                $("#translated").html(response.data.translations[0].translatedText);
 
            },"json") .fail(function(jqXHR, textStatus, errorThrown) 
            {
                alert( "error :"+errorThrown );
            });
    }
    </script>
  
  </body>
</html>

403 error means that you have permission issues. I tried running your code and it works fine for me, I used an API key of mine with no restrictions.

Test done without API key restrictions:

在此处输入图像描述

I tried adding restrictions on my API key like only "allowing requests for Cloud Storage" as an example and I get your 403 error.

Test done using an API key with API restrictions. As you can see "Hindi" translation did not push through due to the applied restriction:

在此处输入图像描述

I suggest to double check your API key setup if there are existing Application or API restrictions and adjust them accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM