Search code examples
node.jsibm-cloudtone-analyzer

Invalid credentials problem when consumig tone analizer from a nodejs app


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"}]}}

Solution

  • 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',
    });