CORS Issues with Google Vision API Calls

穿精又带淫゛_ 提交于 2019-12-11 08:54:34

问题


I am making a call to Google's Vision API using Ajax. I have completed billing and received an API key. However once implemented, I am getting errors like this:

"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403."

I have tried using solutions I found online like setting the request header to "Access-Control-Allow-Origin: *" and using a Chrome Extension. If anybody can help that would be excellent.

var request = {     
    "requests": [{
              "image": {
                "content": url,
              },
              "features": [{
                  "type": "WEB_DETECTION",
                  "maxResults": 1
               }]
            }]
     }

$.ajax({
     method: 'POST',
     url: 'https://vision.googleapis.com/v1/images:annotate?key=' + key,
     contentType: 'application/json',
     data: JSON.stringify(request),
     processData: false,
     beforeSend: function(req) {
         req.setRequestHeader('Access-Control-Allow-Origin', '*');
         console.log(req);
     },
     success: function(data){
         console.log("Data: " + data);
         var webData = data.responses[0].webAnnotations[0];
         console.log("Web Data: " + webData);
     },
     error: function (data, textStatus, errorThrown) {
         console.log('error: ' + errorThrown);
     }
}); 


回答1:


I'm going to summarise the discussion in the comments here:

When making cross domain API calls if the website file is opened using the file:// protocol, the API calls are usually rejected by the browser. To circumvent this, try running a local server and accessing it from there.

I usually use the npm package http-server

npm i -g http-server
cd /path/to/folder/with/static/files
http-server

Your website will be accessible at http://localhost:8080

EDIT: You will need NodeJS installed to use npm

If you don't have NodeJS, you could also install Apache or Nginx or XAMPP to do the same thing.

There is also a handy service called Surge.sh which allows you to easily deploy a website to a custom subdomain on surge.sh.



来源:https://stackoverflow.com/questions/49912384/cors-issues-with-google-vision-api-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!