3

So, I am working with node.js for consume one API of IBM Cloud. I have this code and with that, I can to visualize the response but, I need pass this "res.send" to HTML. So, how can I do it?

This is my code in Node.js. Thank you!

var express = require('express');
var path = require('path');
var app = express();


app.listen(2000, function () {
  console.log(' Watson!');
});

//---------------

app.get('/', (req, res) => {

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

var tone_analyzer = new ToneAnalyzerV3({
  username: '',
  password: '',
  version_date: '2017-09-21',
  accept_language: 'es',
  tone_name: 'es'
});

var params = {
  'tone_input': require('./tone.json'),
  'content_type': 'application/json',
  'content_language' : 'en',
  'accept_language' : 'es'
};

tone_analyzer.tone(params, function(err, response) {
  if (err){
    console.log('error:', err);
    res.send(err);
  }
  else{

    res.render('index.html');
    res.send({"Hi! I'm Waton and I can see:":response.document_tone.tones[0].tone_name});
    console.log(JSON.stringify(response, null, 2));
}
  });

});
Isaac Alejandro
  • 247
  • 1
  • 3
  • 8
  • res.send sends a JSON response to your client's application. Your client's application displays it. – SILENT Apr 05 '18 at 01:04
  • It is not clear what you're trying to accomplish. If you want to insert data into `index.html` before sending it, then you would typically use a template engine that you would pass the HTML template and the data to and the template engine would insert the data according to your template design. You cannot call both `res.render()` and `res.send()`. Only the first one you call will send anything. – jfriend00 Apr 05 '18 at 01:27

2 Answers2

0

I think you want this format which renders the view and pass the local variable to the view

res.render(view [, locals] [, callback])

Here's a good example

Jamal
  • 23
  • 5
0

Your code must return a HTTP response to the client (web browser). Therefore you have some options related to different functions that can be called on the Express response object (res in your case). See here for more information about that.

You could use res.send([body]) just like you did: this will write in the HTTP response body the string you created appending the value returned by Tone Analyzer. However this will just return a blank page with that string and maybe this is not you want in case of a more complex web application with its specific look and feel. In this case you could use a template engine that will append the values of the variables of your choice to the static HTML code of a page (view). See Using template engines with Express for more info.

Please note that whatever is the solution you choose, obviously you can send the HTTP response back to the client only once, therefore you must choose only one of the above mentioned options.

Umberto Manganiello
  • 3,213
  • 9
  • 16