Can't access IBM Watson API locally due to CORS in Rails / AJAX application
There don't seem to be many answers (but many questions) on how to deal with this, so I'm going to add my name to the chorus and pray for an answer that Node.
My error via Chrome console:
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.
I am using Rails AJAX request as such:
$.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.")
}
});
For this particular prototype application, I have Rack :: Cors built to make something work. This is in my .rb app:
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
Is there anyone who knows how to configure this to get around this? I have to assume that there is access to these APIs without having to start an instance of Node.
source to share
The following services support CORS :
- Analytics of compromise
- Sentiment analyzer
- Speech to text
- Text to speech
- Personality Insights
- Converting documents
- All Alchemy services
- Conversation
- Understanding natural language
The following services do not support CORS
- Language translator
- Visual recognition (partial support)
- Get and rank
We are working on adding support for the rest of the services.
As @ brian-martin suggested, you shouldn't use your credentials in the browser. Something you can do is get a token using an authorization service and then use that token instead of a username and password. Take a look at this tutorial on how to use tokens
UPDATE 04/07: Added a list of services that support CORS (thanks to Nathan)
source to share