[英]Pass Node.js array from endpoint to Javascript function
我有一個 html 圖表,它將顯示來自 javascript function 'window.testDataArray' 的數組。 我想用來自服務器端點的數組數據替換示例數組。 我不確定我需要做什么才能實現這一目標。
客戶端
window.testDataArray = function(){
return [6.5,5.2,3.4,5.8] //sample array
};
更新的客戶端(不工作)我不確定這里的語法是否正確。 非常歡迎任何幫助。 我對 javascript 和 node.js 非常陌生。
window.testDataArray = async function(){
// return [1,2,3,4,5,6,7,8,9,9,8,7,4,5,6,1,2,3]
try{
return await fetch('http://localhost:3000/array').then(function (data) {
return data
}).catch(function(error){return 'testDataArray' + (error)
});
}
catch(error){'Error testDataArray' + error}
};
服務器端
const express = require('express');
const app = express();
app.get('/array', (req, res) => {
test()
async function test (){
res.send(await local_db.get_data('heights'));//returns array e.g.[5.1,4.3,2.1,5.8]
}
//await local_db.disconnect();
})
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
//console.log("Server running at http://127.0.0.1:3000/ or http://localhost:3000/");
“window.testDataArray”在 utlis.js 中,並從“Line Chart.html”中調用。 window.testDataArray 無法從 node.js 服務器端點http://localhost:3000/array獲取數組
回復下面的答案(無法在本地重現答案我錯過了什么?)
感謝特使的解釋,您的代碼就像一個魅力,但我無法讓它與本地服務器一起使用。 我不打算將此上傳到 web。 瀏覽器對 runkit 端點的響應是'Cannot GET /'
。 但是當我導航到'http://localhost:3000/array'
我得到[0,10,5,2,20,30,45]
。 請在下面查看您的代碼。 我已將您的 runkit 端點替換為本地端點。
<!DOCTYPE html>
<!-- saved from url=(0061)https://www.chartjs.org/samples/latest/charts/line/basic.html -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Line Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="myChart"></canvas>
<style>
@keyframes chartjs-render-animation{from{opacity:.99}to{opacity:1}}.chartjs-render-monitor{animation:chartjs-render-animation 1ms}.chartjs-size-monitor,.chartjs-size-monitor-expand,.chartjs-size-monitor-shrink{position:absolute;direction:ltr;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1}.chartjs-size-monitor-expand>div{position:absolute;width:1000000px;height:1000000px;left:0;top:0}.chartjs-size-monitor-shrink>div{position:absolute;width:200%;height:200%;left:0;top:0}</style></head>
<body>
<script>
const chart = new Chart(
document.getElementById('myChart').getContext('2d'),
{
type: 'line',
// ...
}
)
//const API_HOST = 'https://so-58465005-mqksg0z5tsf8.runkit.sh'
const API_HOST = 'http://localhost:3000'
fetch(`${API_HOST}/array`)
.then(response => response.json())
.then(data => {
chart.config.data.labels = Array.from(Array(data.length)).map((_, i) => i + 1)
chart.config.data.datasets.push({ label: 'my data', data })
chart.update()
})
</script>
</body></html>
請在下面找到服務器端代碼。 我已將 '@runkit/runkit/express-endpoint/1.0.0' 替換為 'express'。 我一定在這里遺漏了一些基本的東西嗎? 再次感謝您迄今為止的幫助。
const express = require("express")
const cors = require('cors')
const app = express()
app.use(cors())
app.get("/array", (req, res) => {
const data = [0, 10, 5, 2, 20, 30, 45]
res.send(JSON.stringify(data))
res.end();
})
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
``
首先,您原始帖子的評論很有幫助,您絕對應該了解 JavaScript 中的異步編程。
但是,我繼續寫了這個片段。 您可能會發現它很有用。
const getHTMLChart = async () => {
const response = await fetch('http://localhost:3000/array', {
method: 'GET',
});
const data = await response.json();
console.log(data) // This should be what you're looking for.
return data
};
如果您需要更多信息,請與我們聯系。
您的項目存在一些問題,我已經在 RunKit 上復制了您的服務器- 請注意兩個重要組件:
JSON
完成。.html
文件,但看起來您可能會遇到跨域錯誤 - 我包含了處理此問題的中間件,進一步閱讀 CORS 可在此處獲得。 為了解決問題中描述的問題,您目前正嘗試在請求響應之前將數據靜態應用於配置。 而是嘗試對fetch
返回的 promise 中的數據做出反應。
現在忘記async
/ await
,這可以通過將回調 function 傳遞給.then
來實現 - 類似於您在附加示例中其他地方已經響應按鈕單擊事件的方式。
const chart = new Chart( document.getElementById('myChart').getContext('2d'), { type: 'line', //... } ) const API_HOST = 'https://so-58465005-mqksg0z5tsf8.runkit.sh' fetch(`${API_HOST}/array`).then(response => response.json()).then(data => { chart.config.data.labels = Array.from(Array(data.length)).map((_, i) => i + 1) chart.config.data.datasets.push({ label: 'my data', data }) chart.update() })
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> <canvas id="myChart"></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.