通过调用服务器端 javaScript 从 Node.JS Express 中的静态文件写入文件



我有一个node.js项目,我可以从app.js文件写入文件。App.js 启动服务器并运行我的公用文件夹中的索引.html的内容。问题是我无法从公用文件夹中的javascript写入文件,我想这是因为那里的所有javascript都是客户端。如何调用服务器端 javascript 以便我可以执行 I/O?

索引.html - 位于公用文件夹中

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>test1</title>
</head>
<body>
<button onclick="WriteToFile()">writie to file</button> <br>
</body>
</html>

应用.js

var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
// set static path
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, function(){
console.log('Server started on Port 3000...');
})
//How do i call this function or write to a file from index.html.
function WriteToFile(){
fs = require('fs');
fs.writeFile('helloworld.txt', 'The Function was called', function (err) {
if (err) 
return console.log(err);
console.log('Wrote Hello World in file helloworld.txt, just check it');
});
}

如何调用服务器端 JavaScript 以便我可以执行 I/O?

你没有。从来没有,从来没有。

如果客户端和服务器端之间存在分离,这是有原因的。安全性主要是,但也关注点分离。

虽然 node.js 允许您呈现视图,但它仍然是一个后端框架,后端和生成的前端不会以任何方式链接。 即使是像 Rails 这样的单体框架,看起来后端和前端只有一个块是分开的,它们只是有非常好的抽象来隐藏两者之间的分离。

您需要在 express 中创建一个将执行所述函数的路由。

app.get('/hello-world', function(){
// Insert your logic here
})

然后在前端,使用 Axios(更简单(或 fetch API(更多样板但本机函数,无需外部模块(调用此端点。

最新更新