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

2023-11-29

关于如何处理这个问题似乎没有很多答案(但有很多问题),所以我将把我的名字添加到合唱中,并祈祷得到一个不涉及 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 建议的那样,您不应在浏览器中使用您的凭据。您可以做的就是使用授权服务获取令牌,然后使用该令牌代替用户名和密码。看看这个教程,了解如何使用tokens

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐