[英]Node/Express, passing data to the front-end
讓這個工作特別困難。 我已經閱讀了關於這個主題的無數其他帖子(其中大多數使用前端框架,或者從快速模板引擎(.ejs、.jade、車把等)渲染視圖。我使用的是基本的.html 文件與 ajax。
我有一個快速應用程序,用於從外部 API 請求和解析數據。 “/”路由為.html 頁面提供服務,我還有一個“/getDeviceStatusAll”路由將 GET 請求發送到 API 並將響應解析/格式化為數組。 我想將此數組提供給我的前端,它將這些數據顯示在一個漂亮的可搜索表中。
應用程序.js:
const express = require('express');
const app = express();
const path = require('path');
const port = 1337;
var reqs = require('./reqs.js');
var logger = require('./logger.js');
app.get('/', function(req, res){
logger.log('homepage loaded.');
res.sendFile(path.join(__dirname, '/views/wallboard.html'));
});
app.get('/getDeviceStatusAll', (req, res) => {
//api request to retrieve device status for all devices.
let d = reqs.getDeviceStatusAll();
res.send(d);
});
app.listen(port, () => {
logger.printTime('Application started.');
logger.log('Application started.');
})
reqs.js(只是組織 GET 請求代碼的另一個模塊)
var request = require('request');
const fs = require('fs');
var method = 'GET';
var ds_URL = 'https://example.com/api/getDeviceStatus';
var APIKEY = 'TmlGd0lMUxxxxxxxxxYjhNM3djUT09';
var ds_options = {
'method': 'GET',
'url': 'https://example.com/api/getDeviceStatus',
'headers': {
'apikey': 'TmlGd0lMxxxxxxxxxxxYjhNM3djUT09',
'Content-Type': 'text/plain'
},
body: '{\r\n"devices" : "*"\r\n}'
};
var reqs = {
getDeviceStatusAll: function(){
request(ds_options, function (error, response){
if(error) throw new Error(error);
var body = JSON.parse(response.body);
var data = body["Data"];
dataArr = [];
for(obj of data){
delete obj["unwanted_col1"];
delete obj["unwanted_col2"];
dataArr.push(obj);
}
fs.writeFileSync('./data/getDeviceStatusAll.txt', dataArr);
return dataArr;
})
}
}
module.exports = reqs;
前端視圖/牆板.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://localhost:1337/getDeviceStatusAll"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
th{
color:#fff;
}
</style>
<table class="table table-striped">
<tr class="bg-info">
<th>Bus:</th>
<th>Is Online:</th>
<th>DRID:</th>
<th>Status:</th>
<th>Last Contact:</th>
</tr>
<tbody id="myTable">
</tbody>
</table>
<script>
var dataArray = [];
$.ajax({
method: 'GET',
url: 'http://localhost:1337/getDeviceStatusAll',
success:function(response){
dataArray = response
buildTable(dataArray)
console.log(dataArray)
}
})
function buildTable(data){
var table = document.getElementById("myTable")
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].Bus}</td>
<td>${data[i].Online}</td>
<td>${data[i].DRID}</td>
<td>${data[i].State}</td>
<td>${data[i].LastOnline}</td>
</tr>`
table.innerHTML += row
}
}
</script>
當我加載我的“/”路線時,沒有返回任何內容。 似乎無法弄清楚我做錯了什么。
這是這里的問題。 您的reqs.getDeviceStatusAll
沒有返回值。
let d = reqs.getDeviceStatusAll();
res.send(d);
但是因為請求需要回調,所以你不能簡單地說返回。 你必須傳遞一個回調,比如
// reqs.js
...
var reqs = {
getDeviceStatusAll: function(callback){
request(ds_options, function (error, response){
...
callback(dataArr);
})
}
}
和
// app.js
...
app.get('/getDeviceStatusAll', (req, res) => {
// res.json could also be used here
reqs.getDeviceStatusAll(dataArr => res.send(dataArr));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.