Google Vision API调用的CORS问题 [英] CORS Issues with Google Vision API Calls

查看:93
本文介绍了Google Vision API调用的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ajax调用Google的Vision API.我已完成结算并收到了API密钥.但是一旦实施,我会收到如下错误:

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:

对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头.因此,不允许访问源'null'.响应具有HTTP状态代码403."

"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."

我尝试使用在线找到的解决方案,例如将请求标头设置为"Access-Control-Allow-Origin:*"并使用Chrome扩展程序.如果有人可以帮助,那就太好了.

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);
     }
}); 

推荐答案

我将在此处的评论中总结讨论内容:

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

如果使用file://协议打开了网站文件,则在进行跨域API调用时,API调用通常会被浏览器拒绝.为了避免这种情况,请尝试运行本地服务器并从那里访问它.

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.

我通常使用npm软件包http-server

I usually use the npm package http-server

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

您的网站将可以通过 http://localhost:8080

您需要安装 NodeJS 才能使用npm

You will need NodeJS installed to use npm

如果您没有NodeJS,也可以安装Apache或Nginx或XAMPP来做同样的事情.

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

还有一个方便的服务,名为 Surge.sh ,可让您轻松地将网站部署到上的自定义子域urge.sh.

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

这篇关于Google Vision API调用的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆