简体   繁体   English

如何将node.js传递给html?

[英]How to pass of node.js to html?

So, I am working with node.js for consume one API of IBM Cloud. 因此,我正在使用node.js来使用IBM Cloud的一个API。 I have this code and with that, I can to visualize the response but, I need pass this "res.send" to HTML. 我有这段代码,有了它,我可以可视化响应,但是,我需要将此“ res.send”传递给HTML。 So, how can I do it? 那么,我该怎么办呢?

This is my code in Node.js. 这是我在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));
}
  });

});

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 这是一个很好的例子

Your code must return a HTTP response to the client (web browser). 您的代码必须向客户端(Web浏览器)返回HTTP响应。 Therefore you have some options related to different functions that can be called on the Express response object ( res in your case). 因此,您有一些与不同功能相关的选项,可以在Express响应对象上调用(在您的情况下为res )。 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 . 您可以像使用一样使用res.send([body]) :这将在HTTP响应主体中写入您创建的字符串,并附加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. 但是,这只会返回带有该字符串的空白页,对于具有特定外观的更复杂的Web应用程序,可能不希望这样做。 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). 在这种情况下,您可以使用模板引擎,该引擎会将您选择的变量的值附加到页面(视图)的静态HTML代码中。 See Using template engines with Express for more info. 有关更多信息,请参见将模板引擎与Express一起使用

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. 请注意,无论选择哪种解决方案,显然您只能将HTTP响应发送回客户端一次,因此,您只能选择上述选项之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM