getting CORS error when using IBM Watson personality insight service

1.4k Views Asked by At

I am creating a web react web service that needs IBM watson personality insight service. documented here

This is my request

var test = "some string";
var myHeaders = new Headers();
myHeaders.append("authorization",config.ibmCredential);
myHeaders.append("Content-type", "text/plain");
myHeaders.append("Accept", "application/json");
myHeaders.append("Access-Control-Allow-Origin","*");
var myRequest = { method: 'POST', headers: myHeaders, body: test}

and I call it via:

async postData() {
const data = await fetch(`${config.ibmURL}`,myRequest);

and the result Firefox console gives me is:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://gateway.watsonplatform.net/personality-insights/api/v3/profile?version=2018-10-20. (Reason: missing token ‘access-control-allow-origin’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).

I also tried to obtain a token to use instead of sending credentials. However, Firefox consoles only provided me with this, which I don't know what it is nor how to use it.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://gateway.watsonplatform.net/authorization/api/v1/token?url=https://gateway.watsonplatform.net/personality-insights/api. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

*Note that both of these requests work well with Postman

1

There are 1 best solutions below

0
On

sideshowbarker comments are correct - you do not want to set the Access-Control-Allow-Origin header; that's true of all CORS requests.

Additionally, for Watson CORS requests, you cannot set an Authorization header, because this would leak your private credentials to your end users.

Instead, you must use Auth Tokens, which requires a small amount of server-side code.

Your server-side code makes a request with your private credentials and then obtains a temporary auth token that can be exposed to clients. The client sets it in either an X-Watson-Authorization-Token header or else a watson-token querystring param.

Note that the token comes url-encoded, so you should take care not to double-encode it if using it in a querystring.

In general, I'd recommend using the SDK when possible - you can combine the webpack and Persionality Insights examples to achieve your goal of using Personality Insights from client-side code.