javascript - 节点服务器无法访问对象块(面向对象的 javascript)
问题描述
我正在尝试制作一个可以通过高度访问每个块对象的节点服务器,所以这里是获取路由:
// Enpoint to Get a Block by Height (GET Endpoint)
getBlockByHeight() {
this.app.get("/block/height/:height", async (req, res) => {
if(req.params.height) {
const height = parseInt(req.params.height);
let block = await this.blockchain.getBlockByHeight(height);
if(block){
return res.status(200).json(block);
} else {
return res.status(404).send("Block Not Found!");
}
} else {
return res.status(404).send("Block Not Found! Review the Parameters!");
}
});
}
这是获取块高度的函数:
getBlockByHeight(height) {
let self = this;
return new Promise((resolve, reject) => {
let block = self.chain.filter(p => p.height === height)[0];
if(block){
resolve(block);
} else {
resolve(null);
}
});
}
这是block.js:
const SHA256 = require('crypto-js/sha256');
const hex2ascii = require('hex2ascii');
class Block {
// Constructor - argument data will be the object containing the transaction data
constructor(data){
this.hash = null; // Hash of the block
this.height = 0; // Block Height (consecutive number of each block)
this.body = Buffer.from(JSON.stringify(data)).toString('hex'); // Will contain the transactions stored in the block, by default it will encode the data
this.time = 0; // Timestamp for the Block creation
this.previousBlockHash = null; // Reference to the previous Block Hash
}
validate() {
let self = this;
return new Promise((resolve, reject) => {
// Save in auxiliary variable the current block hash
let currentHash= self.hash
// Recalculate the hash of the Block
let newHash =SHA256(JSON.stringify(self))
// Comparing if the hashes changed
if(newHash===currentHash){
resolve("Block is valid")
}else{
// Returning the Block is not valid
reject("Block is not valid")
}
// Returning the Block is valid
});
}
getBData() {
let self = this;
// Getting the encoded data saved in the Block
// Decoding the data to retrieve the JSON representation of the object
// Parse the data to an object to be retrieve.
let data=hex2ascii(self)
// Resolve with the data if the object isn't the Genesis block
let object=JSON.parse(data)
return new Promise((resolve, reject) => {
if(self.previousBlockHash==!null){
resolve(object)
}else{reject()
}
});
}
}
module.exports.Block = Block;
当我运行服务器时,我在控制台中没有收到任何警告,我在此处附加了一个针对该问题的存储库:https ://github.com/Mai9550/privateBlockchain2
解决方案
在getBlockByHeight()
in 中BlockchainController.js
,您正在为
/block/height/:height
这将不会处理以下请求:
/block/0
路线代码正在等待
/block/height/0
因此,您要么从客户端请求错误的 URL,要么您的服务器代码配置了错误的路由规范。
推荐阅读
- reactjs - 谁能告诉我两个函数的区别?
- javascript - 如何在外部窗口/选项卡中共享材质 ui 组件和样式
- reactjs - 是否可以使用 QRCode 下载 json 数据(包含视频、图像、音频等的路径)并将 js 从浏览器响应到移动设备?
- database - MongoDB - 查找多个字段不存在于另一个集合中的文档
- go - 将 [][] 字符串转换为 [] 字节
- rest - RESTful 路由 - 路由不支持所有 CRUD 操作
- mysql - 用于连接具有最新更改的表的 Mysql 优化
- node.js - AWS v2 和 v4 签名 URL
- ruby-on-rails - Rails minitest 在 has_many 验证中失败
- android - 如何基于 Xamarin 表单中的当前页面广播消息