简体   繁体   中英

Consuming restfull api and share the result to web page using Node.js

I am trying to request data from RESTful API and sharing the result to html web page using Node.js. My code runs well, but I want to make this RESTful request every time I call the webpage not just when I run a Node.js server.

var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
var request = require("request");
var temp = "";

var options = { method: 'GET',
  url: 'My_URL',
  headers: { authorization: 'Basic My_Autho' } 
};

request(options, function (error, response, body) {
  if (error) throw new Error(error);
  temp = body;
  console.log(body);
});

http.createServer(function(req,res) {
  res.writeHead(200, {'Content-Type': 'text/html'
});

fs.readFile('index.html', 'utf-8', function(err, content) {
if (err) {
  res.end('error occurred');
  return;
}

var renderedHtml = ejs.render(content, {temp: temp});  
res.end(renderedHtml);
});
}).listen(8000);

Maybe you could move your call to the external REST api inside the request handler ?

var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
var request = require("request");
var temp = "";

var options = { method: 'GET',
  url: 'My_URL',
  headers: { authorization: 'Basic My_Autho' } 
};

http.createServer(function(req,res) {
  res.writeHead(200, {'Content-Type': 'text/html'});

  request(options, function (error, response, body) {
    if (error) throw new Error(error);
    temp = body;
    console.log(body);

    fs.readFile('index.html', 'utf-8', function(err, content) {
      if (err) {
        res.end('error occurred');
        return;
      }

      var renderedHtml = ejs.render(content, {temp: temp});  
      res.end(renderedHtml);
    });
  });
}).listen(8000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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