【问题标题】:How to execute HTML-Events with NodeJS?如何使用 NodeJS 执行 HTML 事件?
【发布时间】: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


【解决方案1】:

您可能需要先阅读此answer。由于 JavaScript 是客户端和服务器端的单一语言,当您从 Node.js 开始时可能会引起一些混乱。

但是,这并不意味着您不能在 HTML 中执行 onClick 操作。您当然可以使用 Ajax 或表单提交来完成。我还建议您使用 Express.js 框架。

另外,你不能像这样包含文件 -

<script src="server.js"></script>

因为它不是客户端普通的 JavaScript 文件,即使它具有 .js 扩展名。它是一个服务器端文件。

说到例子,你可以做这样的事情-

const express = require('express');
const app = express();

app.set('view engine', 'ejs');

app.get('/book', function(req, res) {
  res.render('index');
});

当您访问 /book 路线时,它会打开一个索引视图,其中可能有一个表单要提交。然后你可以在 /post POST url 中编写代码来做进一步的修改。

app.post('/book', function(req, res) {
  // req.body will have submitted form data.
  // You can then do modification.
  // You need to use body-parser.
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    相关资源
    最近更新 更多