Generated agent code broken in Node.js
dansteren opened this issue · comments
Describe the bug
Node.js requires a host to be specified when creating an actor using the createActor
method in the generated agent. However, the code generated by dfx generate
doesn't specify a host and therefore breaks as soon as it is imported.
To Reproduce
Steps to reproduce the behavior:
-
Create a simple canister in the language of your choice
-
Generate an agent by running
dfx generate
. This will generate among other things an index.js file containing the lineexport const my_canister_name = createActor(canisterId);
-
Use the generated agent in a simple node.js file. For example:
import { createActor } from "../dfx_generated"; console.log("We break before we even get here."); const hello_world_canister = createActor("rrkah-fqaaa-aaaaa-aaaaq-cai", { agentOptions: { host: "http://127.0.0.1:8000", }, });
-
Run the script with node
-
Note that this results in the following error:
hello_world/node_modules/@dfinity/agent/lib/cjs/agent/http/index.js:141 throw new Error('Must specify a host to connect to.'); ^ Error: Must specify a host to connect to. at new HttpAgent (hello_world/node_modules/@dfinity/agent/lib/cjs/agent/http/index.js:141:23)
Expected behavior
I should be able to import the createActor statement, or the actor directly without everything breaking.
Desktop (please complete the following information):
- Node v18.1.0
- dfx v0.11.0
- JS Agent v0.11.1
Additional context
There is an open forum post with additional details. See https://forum.dfinity.org/t/generated-declarations-in-node-js-environment-break/12686
As a workaround you can manually comment out the last line in the generated index.js, however this is just a bandaid solution.
Also, this is closely related to dfinity/sdk#2240.
This has been resolved by -dfinity/sdk@32c168e
To use the feature in your code, add the setting of
canister -> declarations -> "node_compatibility": true