简体   繁体   中英

ReferenceError with Node.js and Browserify

I try to include this build , in my browser JS with Node.js, here is my server code:

var fs = require("fs");
var http = require("http");
var url = require("url");

http.createServer(function (request, response) {

    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    response.writeHead(200);

    if(pathname == "/") {
        html = fs.readFileSync("views/index.html", "utf8");
        response.write(html);
    } else if (pathname == "/ethereumjs-all.js") {
    script = fs.readFileSync("views/ethereumjs-all.js", "utf8");
        response.write(script);
    } 
    response.end();
}).listen(8000);

console.log("Listening to server on 8000...");

and here is the content of index.html :

<html>
  <head>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="/ethereumjs-all.js"></script>
    <script>
    $(document).ready(function() { 
    var tx = new Transaction()
    ...
    }); // document.ready
    </script>
  </head>
  <body></body>
</html>

However, in the browser console, I get the error ReferenceError: Transaction is not defined The library should have Transaction class defined. So am I using browserify wrong?

Thanks for any help!

From your question, it appears that you are not using Browserify directly; rather, you are using a UMD bundle that has been built using Browserify.

When a UMD bundle is included in a script element, its module is exposed via a global - a property added to window . In this case the global/property is named EthJS . If you log that using console.log(EthJS) , you should see this:

Object
  ABI:()
  Account: function (data)
  BN: function BN(number, base, endian)
  Block: function (data)
  Buffer: function Object
  ICAP: function Object
  RLP: function Object
  Trie: function CheckpointTrie()
  Tx: function (data)
  Units: Object
  Util: Object
  VM: function VM(trie, blockchain, opts)
  Wallet: function (priv, pub)
  WalletHD: function EthereumHDKey()
  WalletThirdparty: Object

Which suggests that the transaction constructor is named Tx , so your code should likely be:

<script>
$(document).ready(function() { 
    var tx = new EthJS.Tx(...);
    ...
}); // document.ready
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM