首页 > 解决方案 > 无法从节点 js 客户端 + rest api spring boot 重定向到响应数据

问题描述

问题:我已经定义了一个简单的索引页面,它有 2 个输入字段,在提交时它使用节点 js 中的 http.request(get 方法) 来调用作为 spring boot 运行的 rest api,我可以从 rest 中返回响应api spring boot 以及我可以在 res.on 中打印它。

但是,我需要将此数据重定向或呈现到另一个我无法实现的html (output.htm)页面,需要您的输入/帮助。

节点 js (- http://localhost:8081/index.htm )

<html>
   <body>

      <form action = "http://127.0.0.1:8081/grafanacpustats" method = "GET">
         Stats Name: <input type = "text" name = "statsname">  <br>
         Server Name: <input type = "text" name = "hostname">
         <input type = "submit" value = "Submit">
      </form>

   </body>
</html>

nodejs(输出.htm)

<html>
   <body>

         Server Name : {{ data.servername }}
         CPU Statistics : {{ data.cpu }}

   </body>
</html>

ex2.js

var express = require('express');
var Request = require("request");
var http = require("http");

var app = express();

app.use(express.static('public'));

app.get('/', function (req, res) {
    resp.send("");
})

app.get('/index.htm', function (req, res) {
   res.sendFile( __dirname + "/" + "index.htm" );
})


app.get('/stats', function (req, resp) {
   // Prepare output in JSON format
   requestParams = {
      statsname:req.query.statsname,
      hostname:req.query.hostname
   };

    console.log(req.query.statsname);
    console.log(req.query.hostname);

    var statsname = req.query.statsname;
    var hostname = req.query.hostname;
    var responseText;


    var options = {
      host: "10.96.1.17",
      port: 8080,
      path: '/CPUStatus?statsName=' + statsname + '&serverName=' + hostname,
      method: 'GET'
    };

    http.request(options, function(res) {
      console.log('STATUS: ' + res.statusCode);
      console.log('HEADERS: ' + JSON.stringify(res.headers));
      res.setEncoding('utf8');

    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
        responseText = chunk;
      });

        //resp.send(responseText);
        resp.render(__dirname + '/output.htm', { 'data.servername': hostname , 'data.cpu' : responseText});

    }).end();


    resp.send("hello");


});

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   console.log("Example app listening at http://%s:%s", host, port)
})

标签: node.jsspring-boot

解决方案


我已经通过使用jade渲染解决了这个问题,而且我创建了一个服务,以便块执行并等待来自rest api的响应。


推荐阅读