0

i want to know why i can not print the results of my node js code in HTML. If run the program from the command prompt for Node everything is ok, but when i tried to do it in HTML in a web page i can´t.

This is my code:

<!DOCTYPE html>
<html>
<body>

<h1> Translation </h1>
<p> My first Translation </p>



<script>


var watson = require('watson-developer-cloud');

var language_translation = watson.language_translation({
  username: 'bff2a4a9-3e8c-4915-bb54-d8b2a1bbff91',
  password: 'w0mXMEU1PnsZ',
  version: 'v2'
});

language_translation.translate({

  text: 'A sentence must have a verb', source : 'en', target: 'es' },
  function (err, translation) {
    if (err)
      document.write('error:', err);
    else
      document.write(JSON.stringify(translation, null, 2));
});

language_translation.identify({
  text: 'The language translation service takes text input and identifies the language used.' },
  function (err, language) {
    if (err)
      document.write('error:', err);
    else
      document.write(JSON.stringify(language, null, 2));
});

</script>


</body>
</html>
mijares93
  • 59
  • 8

2 Answers2

2

Node is a server-side runtime for JavaScript. You can't put it in a <script> tag like that.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
1

Due to CORS, the browser will not allow you to make a call like this to another server. Furthermore, you cannot use the require method in the browser without support (more info here).

You need to put this code onto a Node.js server for it to execute and the Watson API to respond (see examples here). Once you receive the response, you can populate your HTML page with this information. There are many ways to setup this flow and that is an all together different topic.

Also - I hope the username/password you included in your code sample is not your actual credentials. If so, change them immediately.

Community
  • 1
  • 1
Ben Rondeau
  • 2,983
  • 1
  • 15
  • 21
  • 1
    +1 about the credential, and change the credential on website you have signed for with thoses, a edit will not be enought to hide this. – DrakaSAN Jan 21 '16 at 21:23