javascript - 为 html 网页使用 nodejs 模块
问题描述
我正在开发一个 Base64 编码字符串,然后对其进行哈希处理的小项目。
我正在使用 Nodejs 来托管服务器:
#!/usr/bin/env nodejs
var http = require('http');
var fs = require('fs');
function onRequest(request, response){
response.writeHead(200,{'Content-Type': 'text/html'});
fs.readFile('./index.html',null, function(error, data){
if (error) {
response.writeHead(404);
response.write('file not found');
} else {
response.write(data);
}
response.end();
});
}
http.createServer(onRequest).listen(8000);
console.log('server is running!');
在 HTML 页面上,我创建了一个表格,其中左侧单元格是编码数据,右侧单元格是哈希值。
<div class="container">
<table id="table" class="table">
<thead>
<tr>
<th>Encode</th>
<th>Encrypt</th>
</tr>
</thead>
</table>
</div>
要生成值,我使用以下内容:
<button onclick="addData()">Add a Row</button>
该脚本在 HTML 的顶部引用。
最后,这是在单击按钮时填充单元格的 JS:
function addData(){
var table = document.getElementById("table");
var row = table.insertRow(1); //which number row the data is added from. row 0 is for the titles.
var cell1 = row.insertCell(0); //left cells
var cell2 = row.insertCell(1); //right cells
cell1.innerHTML = encode("value");
cell2.innerHTML = encrypt("value");
}
如果我删除encode
并且encrypt
只提供一个值,它就可以工作。但是当我介绍我的两个函数进行编码然后加密时,HTML 会打印出整个函数。
功能:
function encode(string) {
let buff = new Buffer(string);
let base64data = buff.toString('base64');
return base64data;
}
function encrypt(string) {
let crypto = require('crypto');
let hash = crypto.createHash('sha512').update(string).digest('base64');
return hash;
}
我得到的错误是:
ReferenceError: Buffer is not defined[Learn More]
所以我的问题是,为什么我不能使用使用 nodeJS 模块的函数?
解决方案
推荐阅读
- google-apps-script - 带有编码的 Google 表格 IMPORTDATA
- android - 在实时应用程序中反应本机 udp 问题
- javascript - React Auth:承载未定义(401未授权)
- django - Django MultiSelectField 如何在表单中设置 disabled=True
- flutter - Row Flutter 内的响应式容器
- apache-camel - 当肥皂故障时,Camel cxf 导致 I/O 调度程序线程 100% CPU
- html - WordPress Bootstrap5 Navbar 未与其他 col div 对齐
- mysql - MySQL 在添加新的复合索引时是否会在表上获得锁?
- c# - 如何在elasticsearch中将字段类型从字符串更新为字符串数组?
- c# - ASP.NET CORE / 添加 .AddSignInManager 时遇到的问题
>(); 在启动类