由于Rails / AJAX应用程序上的CORS,无法在本地访问IBM Watson API

似乎没有很多关于如何处理这个问题的答案(但很多问题),所以我要将我的名字添加到合唱中并祈祷一个不涉及Node的答案。

我的错误来自Chrome控制台:

1. POST https://gateway.watsonplatform.net/visual-recognition-beta/api 2. XMLHttpRequest cannot load https://gateway.watsonplatform.net/visual-recognition-beta/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. 

我正在使用Rails AJAX请求:

 $.ajax({ method: "POST", version: 'v2-beta', url: "https://gateway.watsonplatform.net/visual-recognition-beta/api", password: "-----------", username: "-----------", version_date:'2015-12-02', visual_recognition: [ { name: "visual-recognition-service", label: "visual_recognition", plan: "free", credentials: { url: "https://gateway.watsonplatform.net/visual-recognition-beta/api", password: "----------", username: "---------" } } ], image: "/images/image1.jpg", contentType: 'application/json' }).done(function(msg){ if (200) { console.log("This is a test for if.") } else { console.log("This is a test for else.") } }); 

对于这个特殊的原型应用程序,我让Rack :: Cors设置为让任何东西工作。 这是在我的application.rb中:

 config.middleware.insert_before 0, "Rack::Cors" do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :delete, :put, :patch, :options, :head], :expose => ['access-token', 'expiry', 'token-type', 'uid', 'client', 'auth-token'], :max_age => 0 end end 

那里有没有人知道如何配置这些东西以解决这个问题? 我必须假设有一种方法可以访问这些API而无需启动Node实例。

以下服务支持CORS :

  • 音调分析器
  • 演讲文本
  • 文字转语音
  • 个性见解
  • 会话

以下服务不支持CORS

  • 语言翻译
  • 视觉识别(部分支持)
  • 自然语言理解

我们正在努力增加对其余服务的支持。

正如@ brian-martin建议的那样,您不应该在浏览器中使用您的凭据。 您可以做的是使用授权服务获取令牌,然后使用该令牌而不是用户名和密码。 看看本教程如何使用令牌

更新04/07:添加了支持CORS的服务列表(感谢Nathan) UPDATE 07/10:删除了已弃用的服务

将您的Watson API密钥放在浏览器中是一个坏主意,因为有人可以接受这些密钥,在另一个应用程序中使用它们,并且您将为其访问付费。 您需要从经过身份validation的服务器端应用程序调用API。