首页 > 解决方案 > 为 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 模块的函数?

标签: javascripthtmlnode.jsfunctionbase64

解决方案


推荐阅读