![](/img/trans.png)
[英]Get variable on client-side from the server-side (express.js, node.js)
[英]Get array from node.js (server-side)to react app.js (client-side)
我正在嘗試從node.js
(服務器端)獲取一個數組以響應app.js
(客戶端),因此我需要從node獲取文件到數組並將其發送到app.js
,就像module.exports
從節點並從app.js
導入無法正常工作,這是我嘗試過的
node.js
文件:
const fs= require('fs');
const files=fs.readdirSync('../Movies');
module.exports={
movies:files
}
app.js
文件
import { movies } from "./server/server.js";
console.log(movies);
一定要
你做不到 客戶端中的app.js
,無法導入"./server/server.js"
但是渲染時可以發送具有該文件名的數組。
node.js
:
const files=fs.readdirSync('../Movies');
// when user request your page (this example use ejs)
res.render('<your_ejs_file>', {
myFiles: files,
});
// in your_ejs_file, create variable:
<script>
var yourFiles = <%= JSON.stringify(myFiles)%>
</script>
yourFiles
是命名文件的數組your_folder
如果你想從服務器負載文件,你可以使用AJAX來加載它。
我為您使用變量diffrent的名稱,以免您誤認它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.