Invalid credentials problem when consumig tone analizer from a nodejs app

115 views Asked by At

I'm trying to consume a tone analyzer service from a nodejs app. I get unauthorized access problem, but these credentials work fine when I use them in a curl.

Running locally, in my app.js file I've included the data of the tone analyzer as follows:

var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3');

var toneAnalyzer = new ToneAnalyzerV3({
  version: '2017-09-21',
  iam_apikey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
});

Then I've added this, so my app listens for post requestes in the /tone url:

app.post('/tone', function(req, res, next) {

    var params = {'tone_input': req.body}

    toneAnalyzer.tone(params, function(err, data) {

    if (err) {
      return next(err);
    }
    return res.json(data);
  });
});

But when I call it I get "Unauthorized: Access is denied due to invalid credentials".

The thing is that these credentials work fine in curl:

curl -X POST -u "apikey:XXXXXXXXXXXXXXXXXXXXXXXXXXXXX" --header "Content-Type: application/json" --data-binary @tone.json "https://gateway-lon.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21&sentences=false"
{"document_tone":{"tones":[{"score":0.6165,"tone_id":"sadness","tone_name":"Sadness"},{"score":0.829888,"tone_id":"analytical","tone_name":"Analytical"}]}}
2

There are 2 answers

1
chughts On BEST ANSWER

The reason you are getting unauthorised errors when running locally is that your service is hosted in https://gateway-lon.watsonplatform.net. If you don't specify an endpoint / url in your ToneAnalyzerV3 constructor then the API / SDK defaults to Dallas. So although your credentials may be correct for London, they are not correct for Dallas.

When you deployed your app to the cloud (which I guess was to the London location), you probably bound the service into your application. This sets environment variables allowing the SDK to determine the endpoint.

You constructor should look like:


var toneAnalyzer = new ToneAnalyzerV3({
  version: '2017-09-21',
  iam_apikey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  url: 'https://gateway-lon.watsonplatform.net/tone-analyzer/api',
});

2
Shad On

I don't see problem with code (also never used watson stuff), but you may check the following point :

  • How the request you really send is formated : Because I see that you send param that is not present in your curl request.
  • Is your function using POST aswell (you don't provide much detail on what the call to toneAnalyzer.tone does exactly) ? Maybe it's a conflict of headers or Content-Type.
  • Do you use a proxy (enterprise settings or stuff like that) ? If you do, you may check that node is correctly using it.

You should also provide a bit more details on what exactly your tone object do, and try to find where the call to the IBM API is done.