How take the JSON in Node.JS

I have this in Node.JS file.

var express = require('express');
var app = express();
var http = require('http').Server(app);
var cfenv = require("cfenv");

var appEnv = cfenv.getAppEnv();

http.listen(appEnv.port, appEnv.bind);

var PersonalityInsightsV2 = require('watson-developer-cloud/personality-insights/v2');

var personality_insights = new PersonalityInsightsV2({
  username: '<YOUR-USERNAME>',
  password: '<YOUR-PASSWORD>'
});

personality_insights.profile({
  text: "<YOUR-100-UNIQUE-WORDS>",
  language: 'en' },
  function (err, response) {
    if (err)
      console.log('error:', err);
    else
      console.log(JSON.stringify(response, null, 2));
});

I am sending an API call but as you can see, it shows me the result in JSON in the console. How can I make this result in JSON that shows me in the console, show it to me in an HTML? Thank you very much!

I supose that the problem is in console.log(JSON.stringify(res,null, 2));, but, I don't know how put this in HTML.

Answers:

Answer

It sounds like you're wanting to view the JSON on an HTML page in a browser. Something like this should help. It will start your Express server listening on whatever port you specified using appEnv.port, and will serve up myJson (which will then be assigned in your code)

var express = require('express');
var app = express();
var http = require('http').Server(app);
var cfenv = require("cfenv");

var appEnv = cfenv.getAppEnv();

var myJson;

// respond with JSON when a GET request is made to the index
app.get('/', function (req, res) {
  res.send(myJson)
})

app.listen(appEnv.port);

var PersonalityInsightsV2 = require('watson-developer-cloud/personality-insights/v2');

var personality_insights = new PersonalityInsightsV2({
  username: '<YOUR-USERNAME>',
  password: '<YOUR-PASSWORD>'
});

personality_insights.profile({
  text: "<YOUR-100-UNIQUE-WORDS>",
  language: 'en' },
  function (err, response) {
    if (err)
      console.log('error:', err);
    else
      myJson = JSON.stringify(response, null, 2);
});

To try this, you would open your browser to "http://localhost:appEnv.port/" (where appEnv.port is the port you chose). You should see your JSON output

Answer

You can't just turn JSON into HTML. JSON is a data format. HTML is a markup language. You'll manually have to create some HTML with the way you want it, and then drop in values from the JSON.

For example, you could do something like this:

else {
  const html = 
    `<!DOCTYPE html>
     <body>
     <p>${response.name}</p>
  `;
  console.log(html);
}

That would give you some HTML like:

<!DOCTYPE html>
<body>
<p>Bob</p>

assuming response has a value of name.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.