【发布时间】:2020-12-08 16:26:27
【问题描述】:
我需要 Nodejs 文件服务器来保存一些文本,但我想用一个用 html 编写的网站来做到这一点。 我怎么能做这样的事情? 这是一个示例,但只有失败:'book() is not defined'。
const http = require('http');
const fs = require('fs');
http.createServer( function (req, res) {
res.writeHead(200,{'Content-Type': 'text/html'})
res.write('<meta charset="utf-8">');
res.write('<button onclick="book(this)">Buchen</button>');
res.end();
}).listen(8080);
function book(sender)
fs.appendFile('test.csv',sender, function (err) {
if (err) {throw err};
console.log("Schreiben erfolgreich");
});
}
当我用script标签连接nodejs文件时,可以处理html文件的代码吗?
<script src="server.js"></script>
如何使用 html 按钮执行 nodejs book() 函数?
【问题讨论】:
-
确定您正在向浏览器发送 2 个标签并调用未在浏览器中定义的函数,但它是 Node.js ?客户端和服务器之间的通信非常复杂——没有直接的客户端/服务器关系。上次使用 pupeteer 进行类似的操作 - Node.js 来填充和运行 PDF.js 查看器。在那里处理PDF并使用exposeFunction将数据发送回Node.js - 例如,标准路径将是加载特殊页面并提交数据。或者您也可以使用 pupeteer(使用间接 WebSocket 通信)。在这里查看我的更改github.com/eltomjan/pdf.js.git
标签: html node.js file server nodejs-server