无法从节点 JS 客户端 + REST API Spring 启动重定向到响应数据



问题: 我定义了一个简单的索引页面,它有 2 个输入字段,提交时使用 Node JS中的http.request(get方法(调用作为Spring Boot运行的REST API,我可以从REST API Spring Boot返回响应,因为我可以在res.on中打印它。

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

Node 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 (output.htm(

<html>
<body>
Server Name : {{ data.servername }}
CPU Statistics : {{ data.cpu }}
</body>
</html>

例2.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)
})

可以将数据存储在本地存储或 cookie 中,然后在新页面中读取它,或者通过查询字符串通过 URL 将此数据传递到另一个页面。

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

最新更新