简体   繁体   English

从node.js(服务器端)获取数组以响应app.js(客户端)

[英]Get array from node.js (server-side)to react app.js (client-side)

I'm trying to get an array from node.js (server-side) to react app.js (client-side) so I need to get files to array from node and send it to app.js it seems like module.exports from node and import from app.js does not work like this here is what I tried 我正在尝试从node.js (服务器端)获取一个数组以响应app.js (客户端),因此我需要从node获取文件到数组并将其发送到app.js ,就像module.exports从节点并从app.js导入无法正常工作,这是我尝试过的

node.js file: node.js文件:

const fs= require('fs');
const files=fs.readdirSync('../Movies');
module.exports={
  movies:files
}

app.js file app.js文件

import { movies } from "./server/server.js";
console.log(movies);

do have have to 一定要

You can't do it. 你做不到 app.js in client, It can't import "./server/server.js" But you can send array has name of file in that forder when render. 客户端中的app.js ,无法导入"./server/server.js"但是渲染时可以发送具有该文件名的数组。

node.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 is array named of file in your_folder If you want load file from server, you can use AJAX to load it. yourFiles是命名文件的数组your_folder如果你想从服务器负载文件,你可以使用AJAX来加载它。

I use name of variable diffrent to you avoid mistake them. 我为您使用变量diffrent的名称,以免您误认它们。

If you want to send data from server-side to the client-side, you can use AJAX (sending HTTP requests to the server using front-end JavaScript). 如果要将数据从服务器端发送到客户端,则可以使用AJAX (使用前端JavaScript将HTTP请求发送到服务器)。 There are also other useful packages that you can use to simplify your work, like request or axios 您还可以使用其他有用的软件包来简化工作,例如请求axios

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM